/**
 * @vitest-environment jsdom
 */
import { renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { createWrapper, newQueryClient } from "./test-utils";
import { useWorkflowSurveyEndings, useWorkflowSurveyOptions } from "./use-trigger-survey-picker";

const { listSurveysMock } = vi.hoisted(() => ({ listSurveysMock: vi.fn() }));

vi.mock("@/modules/survey/list/lib/v3-surveys-client", () => ({
  listSurveys: listSurveysMock,
}));

const page = (data: Array<{ id: string; name: string }>, nextCursor: string | null) => ({
  data,
  meta: { nextCursor },
});

describe("useWorkflowSurveyOptions", () => {
  beforeEach(() => {
    listSurveysMock.mockReset();
  });

  test("walks every cursor page and flattens the surveys", async () => {
    listSurveysMock
      .mockResolvedValueOnce(page([{ id: "s1", name: "One" }], "cursor-1"))
      .mockResolvedValueOnce(page([{ id: "s2", name: "Two" }], null));

    const { result } = renderHook(() => useWorkflowSurveyOptions("ws_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.options).toEqual([
      { id: "s1", name: "One" },
      { id: "s2", name: "Two" },
    ]);
    expect(listSurveysMock).toHaveBeenCalledTimes(2);
    expect(listSurveysMock).toHaveBeenLastCalledWith(expect.objectContaining({ cursor: "cursor-1" }));
  });

  test("keeps each survey's visibility and type, so pickers can refuse a restricted or non-link one", async () => {
    listSurveysMock.mockResolvedValueOnce(
      page(
        [{ id: "s1", name: "One", visibility: "restricted", type: "link" } as { id: string; name: string }],
        null
      )
    );

    const { result } = renderHook(() => useWorkflowSurveyOptions("ws_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.options).toEqual([
      { id: "s1", name: "One", visibility: "restricted", type: "link" },
    ]);
  });

  test("truncates and warns when the cursor never exhausts", async () => {
    const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
    // Always returns a cursor -> the MAX_PAGES break must stop the loop.
    listSurveysMock.mockResolvedValue(page([{ id: "s", name: "S" }], "always"));

    const { result } = renderHook(() => useWorkflowSurveyOptions("ws_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(listSurveysMock).toHaveBeenCalledTimes(20);
    expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("truncated"));
    warnSpy.mockRestore();
  });
});

describe("useWorkflowSurveyEndings", () => {
  beforeEach(() => {
    (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
      true;
    vi.stubGlobal("fetch", vi.fn());
  });

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

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

  test("is disabled (no fetch) when surveyId is falsy", async () => {
    const fetchMock = vi.mocked(global.fetch);
    const { result } = renderHook(() => useWorkflowSurveyEndings(null), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isLoading).toBe(false));
    expect(result.current.endings).toEqual([]);
    expect(fetchMock).not.toHaveBeenCalled();
  });

  test("derives labels for endScreen, redirectToUrl, and fallback endings", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(
      jsonResponse({
        data: {
          defaultLanguage: "en",
          endings: [
            { id: "end-1", type: "endScreen", headline: { en: "<p>Thanks!</p>" } },
            // default-language slot missing -> falls back to any other string value
            { id: "end-2", type: "endScreen", headline: { de: "Danke" } },
            { id: "end-3", type: "redirectToUrl", label: " Go home " },
            // unknown type -> falls back to the id
            { id: "end-4", type: "other" },
            // endScreen whose headline has no usable string -> falls back to the id
            { id: "end-5", type: "endScreen", headline: { en: "   " } },
            // missing id -> filtered out entirely
            { type: "endScreen", headline: { en: "no id" } },
          ],
        },
      })
    );

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.endings).toEqual([
      { id: "end-1", label: "Thanks!" },
      { id: "end-2", label: "Danke" },
      { id: "end-3", label: "Go home" },
      { id: "end-4", label: "end-4" },
      { id: "end-5", label: "end-5" },
    ]);
  });

  test("resolves recall tokens in ending headlines against the survey", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(
      jsonResponse({
        data: {
          defaultLanguage: "en",
          blocks: [
            { id: "b1", elements: [{ id: "q1", headline: { en: "<p>What is your score?</p>" } }] },
            { id: "b2", elements: [{ id: "q2", headline: { en: "Nested #recall:q1/fallback:there#" } }] },
          ],
          variables: [{ id: "v1", name: "plan" }],
          hiddenFields: { enabled: true, fieldIds: ["userId"] },
          endings: [
            { id: "end-1", type: "endScreen", headline: { en: "Thanks! Score: #recall:q1/fallback:none#" } },
            // target deleted -> fallback text, never the raw cuid
            { id: "end-2", type: "endScreen", headline: { en: "Bye #recall:gone/fallback:friend#" } },
            { id: "end-3", type: "endScreen", headline: { en: "Plan #recall:v1/fallback:free#" } },
            { id: "end-4", type: "endScreen", headline: { en: "User #recall:userId/fallback:anon#" } },
            // recalling an element whose own headline recalls -> inner token blanked, not looped on
            { id: "end-5", type: "endScreen", headline: { en: "Q2: #recall:q2/fallback:x#" } },
            // no recall -> unchanged
            { id: "end-6", type: "endScreen", headline: { en: "Plain thanks" } },
          ],
        },
      })
    );

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.endings).toEqual([
      { id: "end-1", label: "Thanks! Score: @What is your score?" },
      { id: "end-2", label: "Bye friend" },
      { id: "end-3", label: "Plan @plan" },
      { id: "end-4", label: "User @userId" },
      { id: "end-5", label: "Q2: @Nested ___" },
      { id: "end-6", label: "Plain thanks" },
    ]);
  });

  // The three recall sources are separate maps merged into one, so a shared id is resolved by merge
  // order alone. Distinct ids in the fixture above cannot catch a reordering; these collisions can.
  test("resolves a colliding recall id by source precedence: hidden field > element > variable", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(
      jsonResponse({
        data: {
          defaultLanguage: "en",
          blocks: [
            {
              id: "b1",
              elements: [
                { id: "shared_qv", headline: { en: "Element headline" } },
                { id: "shared_qh", headline: { en: "Element loses to hidden field" } },
              ],
            },
          ],
          variables: [
            { id: "shared_qv", name: "variable name" },
            { id: "shared_vh", name: "variable loses to hidden field" },
          ],
          hiddenFields: { enabled: true, fieldIds: ["shared_qh", "shared_vh"] },
          endings: [
            { id: "end-1", type: "endScreen", headline: { en: "A #recall:shared_qv/fallback:x#" } },
            { id: "end-2", type: "endScreen", headline: { en: "B #recall:shared_qh/fallback:x#" } },
            { id: "end-3", type: "endScreen", headline: { en: "C #recall:shared_vh/fallback:x#" } },
          ],
        },
      })
    );

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.endings).toEqual([
      // element over variable
      { id: "end-1", label: "A @Element headline" },
      // hidden field (which recalls as its own id) over element
      { id: "end-2", label: "B @shared_qh" },
      // hidden field over variable
      { id: "end-3", label: "C @shared_vh" },
    ]);
  });

  test("falls back to the ending id when a dangling recall leaves the headline empty", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(
      jsonResponse({
        data: {
          defaultLanguage: "en",
          endings: [{ id: "end-1", type: "endScreen", headline: { en: "#recall:gone/fallback:#" } }],
        },
      })
    );

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.endings).toEqual([{ id: "end-1", label: "end-1" }]);
  });

  // Errors rather than resolving to []: an empty success is indistinguishable from "every ending
  // was deleted", and callers that prune stored ids against this list would delete a valid
  // selection. Landing in the error branch keeps them on the "leave it alone" path.
  test("errors when endings is not an array", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(jsonResponse({ data: { endings: "nope" } }));

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isError).toBe(true));
    expect(result.current.isSuccess).toBe(false);
    expect(result.current.endings).toEqual([]);
    expect(result.current.resolvedSurveyId).toBeNull();
  });

  test("throws a parsed error when the response is not ok", async () => {
    const fetchMock = vi.mocked(global.fetch);
    fetchMock.mockResolvedValueOnce(jsonResponse({ status: 404, detail: "Survey not found" }, 404));

    const { result } = renderHook(() => useWorkflowSurveyEndings("survey_1"), {
      wrapper: createWrapper(newQueryClient()),
    });

    await waitFor(() => expect(result.current.isError).toBe(true));
    expect(result.current.endings).toEqual([]);
  });
});
