/**
 * Your custom connector can be tested locally prior to publishing it.
 * In this file, we create a testing harness for our custom connector
 * and we invoke each of our actions to verify that they return expected
 * results.
 *
 * To run just this set of unit tests, run "npm run test -- src/actions.test.ts"
 *
 * For more information on unit tests, see
 * https://prismatic.io/docs/custom-connectors/unit-testing/
 */

import { createConnection, createHarness } from "@prismatic-io/spectral/testing";
import dotenv from "dotenv";
import myComponent from ".";
import { acmeApiKey } from "./connections";

dotenv.config({ path: ".env.testing" });

const harness = createHarness(myComponent);

const acmeConnection = createConnection(acmeApiKey, {
  baseUrl: process.env.ACME_ENDPOINT ?? acmeApiKey.inputs.baseUrl.default,
  apiKey: process.env.ACME_API_KEY ?? "",
});

describe("Test Actions", () => {
  test("Verify listPosts returns the correct number of posts", async () => {
    const result = await harness.action("listPosts", { acmeConnection });
    expect(result?.data).toHaveLength(100);
    expect(result?.data).toEqual(expect.arrayContaining([
      expect.objectContaining({ id: 1, userId: 1, title: expect.any(String), body: expect.any(String) }),
    ]));
  });

  test("Verify getPost returns the correct post", async () => {
    const result = await harness.action("getPost", {
      acmeConnection,
      postId: "3",
    });
    expect(result?.data).toMatchObject({ id: 3, userId: 1, title: expect.any(String), body: expect.any(String) });
  });

  test("Verify addPost creates a sample post to JSONPlaceholder", async () => {
    const result = await harness.action("addPost", {
      acmeConnection,
      title: "My New Post",
      body: "Example body",
      userId: "1",
    });
    expect(result?.data).toMatchObject({ id: 101, title: "My New Post", body: "Example body", userId: 1 });
  });

  test("Verify raw request works as expected", async () => {
    const result = await harness.action("rawRequest", {
      acmeConnection,
      url: "/posts",
      method: "get",
      responseType: "json",
      queryParams: [{ key: "id", value: "2" }],
    });
    expect(result?.data).toEqual([expect.objectContaining({ id: 2, userId: 1 })]);
  });
});
