/**
 * @vitest-environment jsdom
 */
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import type { TCreateWorkflowInput } from "@formbricks/workflows";
import { V3ApiError } from "@/modules/api/lib/v3-client";
import {
  archiveWorkflow,
  buildWorkflowListSearchParams,
  buildWorkflowRunListSearchParams,
  createWorkflow,
  createWorkflowTestRun,
  deleteWorkflow,
  disableWorkflow,
  duplicateWorkflow,
  enableWorkflow,
  getWorkflow,
  getWorkflowRun,
  listWorkflowRuns,
  listWorkflowSamples,
  listWorkflows,
  regenerateWorkflowWebhook,
  replaceWorkflowSecretHeader,
  sendWorkflowTestRequest,
  setWorkflowSample,
  unarchiveWorkflow,
  updateWorkflow,
} from "./api-client";
import { createEmptyWorkflowDefinition } from "./default-workflow";

const workflow = { id: "wf1", name: "x" };
const okResponse = (data: unknown) => ({ ok: true, json: async () => ({ data }) }) as unknown as Response;

const fetchMock = vi.fn();

beforeEach(() => {
  vi.stubGlobal("fetch", fetchMock);
  fetchMock.mockReset();
});

afterEach(() => {
  vi.unstubAllGlobals();
});

describe("webhook, sample and test request calls", () => {
  test("regenerate POSTs and returns the new Secret URL", async () => {
    fetchMock.mockResolvedValueOnce(okResponse({ url: "https://x/webhook/new" }));

    expect(await regenerateWorkflowWebhook("wf1")).toEqual({ url: "https://x/webhook/new" });
    expect(fetchMock).toHaveBeenCalledWith(
      "/api/v3/workflows/wf1/webhook/regenerate",
      expect.objectContaining({ method: "POST" })
    );
  });

  test("setting a sample PUTs it under payload", async () => {
    fetchMock.mockResolvedValueOnce(okResponse({ source: "trigger" }));

    await setWorkflowSample("wf1", { channel: "call" });

    expect(fetchMock).toHaveBeenCalledWith(
      "/api/v3/workflows/wf1/sample",
      expect.objectContaining({ method: "PUT", body: JSON.stringify({ payload: { channel: "call" } }) })
    );
  });

  test("samples are read from the samples list", async () => {
    fetchMock.mockResolvedValueOnce(okResponse([{ source: "call", sample: {}, updatedAt: "x" }]));

    expect(await listWorkflowSamples("wf1")).toEqual([{ source: "call", sample: {}, updatedAt: "x" }]);
    expect(fetchMock).toHaveBeenCalledWith(
      "/api/internal/workflows/wf1/samples",
      expect.objectContaining({ method: "GET" })
    );
  });

  test("replacing a secret PUTs the one value to the step's header", async () => {
    fetchMock.mockResolvedValueOnce({ ok: true, status: 204 });

    await replaceWorkflowSecretHeader("wf1", "call", "Authorization", "Bearer new");

    expect(fetchMock).toHaveBeenCalledWith(
      "/api/internal/workflows/wf1/steps/call/secret-headers/Authorization",
      expect.objectContaining({ method: "PUT", body: JSON.stringify({ value: "Bearer new" }) })
    );
  });

  test("a test request POSTs the draft settings to the step", async () => {
    fetchMock.mockResolvedValueOnce(okResponse({ response: null, error: "timeout" }));

    await sendWorkflowTestRequest("wf1", "call 1", { variables: { payload: { a: 1 } } });

    expect(fetchMock).toHaveBeenCalledWith(
      "/api/v3/workflows/wf1/steps/call%201/test-request",
      expect.objectContaining({ method: "POST", body: JSON.stringify({ variables: { payload: { a: 1 } } }) })
    );
  });
});

describe("getWorkflow", () => {
  test("GETs the workflow endpoint and returns data", async () => {
    fetchMock.mockResolvedValueOnce(okResponse(workflow));
    const signal = new AbortController().signal;

    const result = await getWorkflow("wf1", signal);

    expect(fetchMock).toHaveBeenCalledWith("/api/v3/workflows/wf1", {
      method: "GET",
      cache: "no-store",
      signal,
    });
    expect(result).toEqual(workflow);
  });

  test("throws V3ApiError when response is not ok", async () => {
    fetchMock.mockResolvedValueOnce({
      ok: false,
      status: 404,
      statusText: "Not Found",
      headers: { get: () => null },
      json: async () => ({ detail: "missing" }),
    });

    await expect(getWorkflow("wf1")).rejects.toBeInstanceOf(V3ApiError);
  });
});

describe("updateWorkflow", () => {
  test("PATCHes with JSON body", async () => {
    fetchMock.mockResolvedValueOnce(okResponse(workflow));

    await updateWorkflow("wf1", { name: "new" });

    expect(fetchMock).toHaveBeenCalledWith("/api/v3/workflows/wf1", {
      method: "PATCH",
      cache: "no-store",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: "new" }),
      signal: expect.any(AbortSignal),
    });
  });
});

describe("lifecycle endpoints", () => {
  test.each([
    [enableWorkflow, "enable"],
    [disableWorkflow, "disable"],
    [archiveWorkflow, "archive"],
    [unarchiveWorkflow, "unarchive"],
  ] as const)("POSTs /:id/%s", async (fn, action) => {
    fetchMock.mockResolvedValueOnce(okResponse(workflow));

    await fn("wf1");

    expect(fetchMock).toHaveBeenCalledWith(`/api/v3/workflows/wf1/${action}`, {
      method: "POST",
      cache: "no-store",
      signal: expect.any(AbortSignal),
    });
  });
});

const jsonResponse = (body: unknown, status = 200): Response =>
  new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });

const problemResponse = (status: number, body: unknown): Response =>
  new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/problem+json" } });

describe("buildWorkflowListSearchParams", () => {
  test("encodes workspace, limit, cursor, sort and the filter[...] family", () => {
    const params = buildWorkflowListSearchParams({
      workspaceId: "ws_1",
      limit: 12,
      cursor: "cursor_1",
      filters: { nameContains: "  onboarding  ", statusIn: ["draft", "enabled"], sortBy: "name" },
    });

    expect(params.get("workspaceId")).toBe("ws_1");
    expect(params.get("limit")).toBe("12");
    expect(params.get("cursor")).toBe("cursor_1");
    expect(params.get("sortBy")).toBe("name");
    expect(params.get("filter[name][contains]")).toBe("onboarding");
    expect(params.getAll("filter[status][in]")).toEqual(["draft", "enabled"]);
  });

  test("omits cursor, sort and filters when not provided", () => {
    const params = buildWorkflowListSearchParams({ workspaceId: "ws_1", limit: 12 });

    expect(params.has("cursor")).toBe(false);
    expect(params.has("sortBy")).toBe(false);
    expect(params.has("filter[name][contains]")).toBe(false);
    expect(params.has("filter[status][in]")).toBe(false);
  });

  test("omits a blank or whitespace-only name filter", () => {
    const params = buildWorkflowListSearchParams({
      workspaceId: "ws_1",
      limit: 12,
      filters: { nameContains: "   " },
    });

    expect(params.has("filter[name][contains]")).toBe(false);
  });
});

describe("workflows api-client requests", () => {
  beforeEach(() => {
    vi.stubGlobal("fetch", vi.fn());
  });

  afterEach(() => {
    vi.unstubAllGlobals();
  });

  test("listWorkflows requests the list endpoint and returns the cursor page unchanged", async () => {
    const page = {
      data: [{ id: "wf_1", name: "Workflow 1" }],
      meta: { limit: 12, nextCursor: "cursor_1" },
    };
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse(page));

    const result = await listWorkflows({ workspaceId: "ws_1", limit: 12, filters: { nameContains: "abc" } });

    expect(result).toEqual(page);
    expect(global.fetch).toHaveBeenCalledWith(
      "/api/v3/workflows?workspaceId=ws_1&limit=12&filter%5Bname%5D%5Bcontains%5D=abc",
      expect.objectContaining({ method: "GET", cache: "no-store" })
    );
  });

  test("createWorkflow posts the input and unwraps the resource", async () => {
    const resource = { id: "wf_new", name: "New", status: "draft" };
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: resource }, 201));

    const input: TCreateWorkflowInput = {
      workspaceId: "ws_1",
      name: "New",
      description: null,
      status: "draft" as const,
      definition: createEmptyWorkflowDefinition(),
    };
    const result = await createWorkflow(input);

    expect(result).toEqual(resource);
    const [url, init] = vi.mocked(global.fetch).mock.calls[0];
    expect(url).toBe("/api/v3/workflows");
    expect(init).toMatchObject({ method: "POST", cache: "no-store" });
    // Mutations are timeout-bounded so a stalled request can't hang the editor spinner.
    expect((init as RequestInit).signal).toBeInstanceOf(AbortSignal);
    expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({
      workspaceId: "ws_1",
      name: "New",
    });
  });

  test("duplicateWorkflow posts an empty body when no name is given", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: { id: "wf_copy" } }, 201));

    const result = await duplicateWorkflow("wf_1");

    expect(result).toEqual({ id: "wf_copy" });
    const [url, init] = vi.mocked(global.fetch).mock.calls[0];
    expect(url).toBe("/api/v3/workflows/wf_1/duplicate");
    expect((init as RequestInit).signal).toBeInstanceOf(AbortSignal);
    expect(JSON.parse(String((init as RequestInit).body))).toEqual({});
  });

  test("archiveWorkflow posts to the archive endpoint and unwraps the resource", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: { id: "wf_1", status: "archived" } }));

    const result = await archiveWorkflow("wf_1");

    expect(result).toEqual({ id: "wf_1", status: "archived" });
    expect(global.fetch).toHaveBeenCalledWith(
      "/api/v3/workflows/wf_1/archive",
      expect.objectContaining({ method: "POST", cache: "no-store" })
    );
  });

  test("unarchiveWorkflow posts to the unarchive endpoint and unwraps the resource", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: { id: "wf_1", status: "disabled" } }));

    const result = await unarchiveWorkflow("wf_1");

    expect(result).toEqual({ id: "wf_1", status: "disabled" });
    expect(global.fetch).toHaveBeenCalledWith(
      "/api/v3/workflows/wf_1/unarchive",
      expect.objectContaining({ method: "POST", cache: "no-store" })
    );
  });

  test("deleteWorkflow resolves on a 204 with no body", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(new Response(null, { status: 204 }));

    await expect(deleteWorkflow("wf_1")).resolves.toBeUndefined();
    expect(global.fetch).toHaveBeenCalledWith(
      "/api/v3/workflows/wf_1",
      expect.objectContaining({ method: "DELETE", cache: "no-store", signal: expect.any(AbortSignal) })
    );
  });

  test("maps a problem+json error response to a V3ApiError carrying the detail", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      problemResponse(403, {
        title: "Forbidden",
        status: 403,
        detail: "You are not authorized to access this resource",
        code: "forbidden",
        requestId: "req_1",
      })
    );

    await expect(listWorkflows({ workspaceId: "ws_1", limit: 12 })).rejects.toBeInstanceOf(V3ApiError);
  });

  test("propagates the parsed problem detail and code on a failed mutation", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      problemResponse(400, {
        title: "Bad Request",
        status: 400,
        detail: "The request payload is invalid.",
        code: "bad_request",
        requestId: "req_2",
      })
    );

    await expect(archiveWorkflow("wf_1")).rejects.toMatchObject({
      status: 400,
      code: "bad_request",
      message: "The request payload is invalid.",
    });
  });
});

describe("buildWorkflowRunListSearchParams", () => {
  test("encodes workspace, limit, cursor and the run filter family", () => {
    const params = buildWorkflowRunListSearchParams({
      workspaceId: "ws_1",
      limit: 25,
      cursor: "cursor_1",
      filters: {
        workflowId: "wf_1",
        responseId: "rsp_1",
        statusIn: ["failed", "completed"],
        isDryRun: false,
      },
    });

    expect(params.get("workspaceId")).toBe("ws_1");
    expect(params.get("limit")).toBe("25");
    expect(params.get("cursor")).toBe("cursor_1");
    expect(params.get("workflowId")).toBe("wf_1");
    expect(params.get("responseId")).toBe("rsp_1");
    expect(params.get("filter[isDryRun][eq]")).toBe("false");
    expect(params.getAll("filter[status][in]")).toEqual(["failed", "completed"]);
  });

  test("omits cursor and filters when not provided", () => {
    const params = buildWorkflowRunListSearchParams({ workspaceId: "ws_1", limit: 20 });

    expect(params.has("cursor")).toBe(false);
    expect(params.has("workflowId")).toBe(false);
    expect(params.has("responseId")).toBe(false);
    expect(params.has("filter[isDryRun][eq]")).toBe(false);
    expect(params.has("filter[status][in]")).toBe(false);
  });
});

describe("workflow runs api-client requests", () => {
  beforeEach(() => {
    vi.stubGlobal("fetch", vi.fn());
  });

  afterEach(() => {
    vi.unstubAllGlobals();
  });

  test("listWorkflowRuns requests the runs endpoint and returns the cursor page unchanged", async () => {
    const page = { data: [{ id: "run_1" }], meta: { limit: 20, nextCursor: null } };
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse(page));

    const result = await listWorkflowRuns({
      workspaceId: "ws_1",
      limit: 20,
      filters: { workflowId: "wf_1" },
    });

    expect(result).toEqual(page);
    const [url, init] = vi.mocked(global.fetch).mock.calls[0];
    expect(url).toBe("/api/v3/workflows/runs?workspaceId=ws_1&limit=20&workflowId=wf_1");
    expect(init).toMatchObject({ method: "GET", cache: "no-store" });
  });

  test("getWorkflowRun GETs the run-detail endpoint and unwraps the resource", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: { id: "run_1", logs: [] } }));

    const result = await getWorkflowRun("run_1");

    expect(result).toEqual({ id: "run_1", logs: [] });
    expect(global.fetch).toHaveBeenCalledWith(
      "/api/v3/workflows/runs/run_1",
      expect.objectContaining({ method: "GET", cache: "no-store" })
    );
  });

  test("getWorkflowRun preserves nullable timestamp fields through the round-trip", async () => {
    const resource = {
      id: "run_1",
      logs: [],
      nextAttemptAt: "2026-06-12T11:00:00.000Z",
      lastErrorAt: null,
    };
    vi.mocked(global.fetch).mockResolvedValueOnce(jsonResponse({ data: resource }));

    const result = await getWorkflowRun("run_1");

    expect(result).toEqual(resource);
  });

  test("listWorkflowRuns maps a problem response to a V3ApiError", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      problemResponse(403, {
        title: "Forbidden",
        status: 403,
        detail: "denied",
        code: "forbidden",
        requestId: "req_1",
      })
    );

    await expect(listWorkflowRuns({ workspaceId: "ws_1", limit: 20 })).rejects.toBeInstanceOf(V3ApiError);
  });

  test("getWorkflowRun maps a 403 problem response to a V3ApiError", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      problemResponse(403, {
        title: "Forbidden",
        status: 403,
        detail: "denied",
        code: "forbidden",
        requestId: "req_1",
      })
    );

    await expect(getWorkflowRun("run_x")).rejects.toBeInstanceOf(V3ApiError);
  });

  test("createWorkflowTestRun posts the test payload and unwraps the finished run", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      jsonResponse({ data: { id: "run_t", isDryRun: true } }, 201)
    );

    const result = await createWorkflowTestRun("wf_1", { payload: { channel: "call" } });

    expect(result).toEqual({ id: "run_t", isDryRun: true });
    const [url, init] = vi.mocked(global.fetch).mock.calls[0];
    expect(url).toBe("/api/v3/workflows/wf_1/test-runs");
    expect(init).toMatchObject({ method: "POST", cache: "no-store" });
    expect(JSON.parse(String((init as RequestInit).body))).toEqual({ payload: { channel: "call" } });
  });

  test("createWorkflowTestRun keeps the problem code so a refusal can be explained", async () => {
    vi.mocked(global.fetch).mockResolvedValueOnce(
      problemResponse(422, { status: 422, detail: "No test payload", code: "invalid_workflow_state" })
    );

    await expect(createWorkflowTestRun("wf_1", {})).rejects.toMatchObject({
      status: 422,
      code: "invalid_workflow_state",
    });
  });
});
