import { expect } from "@playwright/test";
import { prisma } from "@formbricks/database";
import { test } from "./lib/fixtures";
import { clearAllFilters, setTableSort, tableRow, toggleQuickFilter } from "./utils/table-toolbar";

const getUserIdForEmail = async (email: string) => {
  const user = await prisma.user.findUnique({
    where: {
      email,
    },
    select: {
      id: true,
    },
  });

  if (!user) {
    throw new Error(`User not found for email: ${email}`);
  }

  return user.id;
};

const getWorkspaceIdsForEmail = async (email: string) => {
  const user = await prisma.user.findUnique({
    where: {
      email,
    },
    select: {
      id: true,
      memberships: {
        select: {
          organizationId: true,
          organization: {
            select: {
              workspaces: {
                select: {
                  id: true,
                },
                take: 1,
              },
            },
          },
        },
        take: 1,
      },
    },
  });

  const membership = user?.memberships[0];
  const workspace = membership?.organization.workspaces[0];

  if (!user || !membership || !workspace) {
    throw new Error(`Workspace not found for email: ${email}`);
  }

  return {
    userId: user.id,
    organizationId: membership.organizationId,
    workspaceId: workspace.id,
  };
};

const createSurveySeed = async ({
  workspaceId,
  userId,
  name,
  status = "draft",
  type = "link",
}: {
  workspaceId: string;
  userId: string;
  name: string;
  status?: "draft" | "inProgress" | "paused" | "completed";
  type?: "link" | "app";
}) => {
  return prisma.survey.create({
    data: {
      workspaceId,
      createdBy: userId,
      name,
      status,
      type,
    },
  });
};

const createResponsesSeed = async ({
  surveyId,
  finished,
  unfinished,
}: {
  surveyId: string;
  finished: number;
  unfinished: number;
}) => {
  const rows = [
    ...Array.from({ length: finished }, () => ({ surveyId, finished: true })),
    ...Array.from({ length: unfinished }, () => ({ surveyId, finished: false })),
  ];

  if (rows.length > 0) {
    await prisma.response.createMany({ data: rows });
  }
};

test.describe("Survey overview", () => {
  test("counts completed responses in the list, and still warns before editing a partial-only survey", async ({
    page,
    users,
  }) => {
    const timestamp = Date.now();
    const email = `overview-completed-${timestamp}@example.com`;
    const name = `overview-completed-${timestamp}`;
    const mixedSurveyName = `Mixed Survey ${timestamp}`;
    const partialsSurveyName = `Partials Survey ${timestamp}`;

    const user = await users.create({ email, name, workspaceName: "Completed Counts Workspace" });
    const userId = await getUserIdForEmail(email);

    await user.login();
    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);
    const workspaceId =
      /\/workspaces\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
      (() => {
        throw new Error("Unable to determine workspace id from surveys URL");
      })();

    const mixedSurvey = await createSurveySeed({
      workspaceId,
      userId,
      name: mixedSurveyName,
      status: "inProgress",
    });
    const partialsSurvey = await createSurveySeed({
      workspaceId,
      userId,
      name: partialsSurveyName,
      status: "inProgress",
    });

    // 5 finished + 6 abandoned: the list must show 5, never the total of 11.
    await createResponsesSeed({ surveyId: mixedSurvey.id, finished: 5, unfinished: 6 });
    // Abandoned only: the list must show 0 while the survey still *has* responses.
    await createResponsesSeed({ surveyId: partialsSurvey.id, finished: 0, unfinished: 2 });

    await page.reload();
    await expect(page.getByText(mixedSurveyName, { exact: true })).toBeVisible({ timeout: 10000 });

    const listHeader = page.getByTestId("survey-list-table").locator("thead");
    await expect(listHeader.getByText("Completed", { exact: true })).toBeVisible();
    await expect(listHeader.getByText("Responses", { exact: true })).toHaveCount(0);

    const mixedRow = tableRow(page, "survey-list-table", mixedSurveyName);
    await expect(mixedRow.getByText("5", { exact: true })).toBeVisible();
    await expect(mixedRow.getByText("11", { exact: true })).toHaveCount(0);

    const partialsRow = tableRow(page, "survey-list-table", partialsSurveyName);
    await expect(partialsRow.getByText("0", { exact: true })).toBeVisible();

    // Regression guard: the caution dialog is driven by the total, so it must still appear for a
    // survey whose displayed count is 0 but which already has (partial) responses.
    await partialsRow.locator("[data-testid='survey-dropdown-trigger']").click();
    // Edit is a Link, not a button; its onClick preventDefaults and opens the caution dialog instead
    // of navigating, precisely because the survey has responses.
    await page.getByRole("link", { name: "Edit", exact: true }).click();
    await expect(page.getByText("Edit an active survey?")).toBeVisible();
  });

  test("loads surveys, applies filters and sort, and paginates with load more", async ({ page, users }) => {
    const timestamp = Date.now();
    const email = `overview-v3-${timestamp}@example.com`;
    const name = `overview-v3-${timestamp}`;
    const targetSurveyName = `Target Survey ${timestamp}`;
    const pausedSurveyName = `Paused Survey ${timestamp}`;
    const appSurveyName = `App Survey ${timestamp}`;
    const paginatedSurveyName = `Paginated Survey ${timestamp}`;
    const user = await users.create({
      email,
      name,
      workspaceName: "Overview Workspace",
    });
    const userId = await getUserIdForEmail(email);

    await user.login();
    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);
    const workspaceId =
      /\/workspaces\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
      (() => {
        throw new Error("Unable to determine workspace id from surveys URL");
      })();

    const surveyDefinitions: Array<{
      name: string;
      status: "draft" | "paused";
      type: "link" | "app";
    }> = [
      { name: paginatedSurveyName, status: "draft", type: "link" },
      { name: "Overview Survey 01", status: "draft", type: "link" },
      { name: "Overview Survey 02", status: "paused", type: "link" },
      { name: "Overview Survey 03", status: "draft", type: "link" },
      { name: "Overview Survey 04", status: "paused", type: "link" },
      { name: "Overview Survey 05", status: "draft", type: "link" },
      { name: "Overview Survey 06", status: "paused", type: "link" },
      { name: "Overview Survey 07", status: "draft", type: "link" },
      { name: "Overview Survey 08", status: "paused", type: "link" },
      { name: "Overview Survey 09", status: "draft", type: "link" },
      { name: appSurveyName, status: "draft", type: "app" },
      { name: pausedSurveyName, status: "paused", type: "link" },
      { name: targetSurveyName, status: "draft", type: "link" },
    ];

    for (const surveyDefinition of surveyDefinitions) {
      await createSurveySeed({
        workspaceId,
        userId,
        name: surveyDefinition.name,
        status: surveyDefinition.status,
        type: surveyDefinition.type,
      });
    }

    await page.reload();
    await expect(page.getByText(targetSurveyName, { exact: true })).toBeVisible({ timeout: 10000 });
    await expect(page.getByText(pausedSurveyName, { exact: true })).toBeVisible();
    await expect(page.getByText(appSurveyName, { exact: true })).toBeVisible();
    await expect(page.getByRole("button", { name: "Load more" })).toBeVisible();
    await expect(page.getByTestId("table-match-count")).toHaveText("14 results");

    await test.step("search narrows the list and survives a reload", async () => {
      await page.getByPlaceholder("Search by survey name").fill(targetSurveyName);
      await expect(page.getByText(pausedSurveyName, { exact: true })).toHaveCount(0);
      await expect(page.getByText(targetSurveyName, { exact: true })).toBeVisible();
      await expect(page).toHaveURL(/search=/);
      await page.reload();
      await expect(page.getByPlaceholder("Search by survey name")).toHaveValue(targetSurveyName);
      await expect(page.getByText(appSurveyName, { exact: true })).toHaveCount(0);
      await page.getByRole("button", { name: "Clear search" }).click();
      await expect(page.getByText(pausedSurveyName, { exact: true })).toBeVisible();
    });

    await test.step("quick filters show as chips, narrow the list and survive a reload", async () => {
      await toggleQuickFilter(page, "Status", "Draft");
      await expect(page.getByText(targetSurveyName, { exact: true })).toBeVisible();
      await expect(page.getByText(pausedSurveyName, { exact: true })).toHaveCount(0);

      await toggleQuickFilter(page, "Type", "Link");
      await expect(page.getByText(appSurveyName, { exact: true })).toHaveCount(0);
      await expect(page).toHaveURL(/filter%5Bstatus%5D%5Bin%5D=draft/);

      await page.reload();
      await expect(page.getByText(appSurveyName, { exact: true })).toHaveCount(0);
      await expect(page.getByText(pausedSurveyName, { exact: true })).toHaveCount(0);
    });

    await test.step("sort comes from the gear and Clear all brings everything back", async () => {
      await setTableSort(page, "Created at");
      await expect(page).toHaveURL(/sortBy=createdAt/);

      await clearAllFilters(page);
      await expect(page.getByText(appSurveyName, { exact: true })).toBeVisible();
      await expect(page.getByRole("button", { name: "Load more" })).toBeVisible();
    });

    await page.getByRole("button", { name: "Load more" }).click();
    await expect(page.getByText(paginatedSurveyName, { exact: true })).toBeVisible();
  });

  test("keeps draft-only actions and optimistically deletes the last survey into the template state", async ({
    page,
    users,
  }) => {
    const timestamp = Date.now();
    const email = `overview-delete-${timestamp}@example.com`;
    const name = `overview-delete-${timestamp}`;
    const surveyName = `Delete Me ${timestamp}`;
    const user = await users.create({
      email,
      name,
      workspaceName: "Delete Workspace",
    });
    const userId = await getUserIdForEmail(email);

    await user.login();
    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);
    const workspaceId =
      /\/workspaces\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
      (() => {
        throw new Error("Unable to determine workspace id from surveys URL");
      })();
    const survey = await createSurveySeed({
      workspaceId,
      userId,
      name: surveyName,
      status: "draft",
      type: "link",
    });

    await prisma.survey.deleteMany({
      where: {
        workspaceId,
        id: {
          not: survey.id,
        },
      },
    });

    await page.reload();
    await expect(page.getByText(surveyName, { exact: true })).toBeVisible({ timeout: 10000 });

    let releaseDeleteRequest: (() => void) | undefined;
    let resolveDeleteStarted: (() => void) | undefined;
    const deleteStarted = new Promise<void>((resolve) => {
      resolveDeleteStarted = resolve;
    });
    await page.route(`**/api/v3/surveys/${survey.id}`, async (route) => {
      resolveDeleteStarted?.();
      await new Promise<void>((resolveDelete) => {
        releaseDeleteRequest = resolveDelete;
      });
      await route.continue();
    });

    await page.locator("[data-testid='survey-dropdown-trigger']").click();
    // Duplicate stays visible for users who can manage surveys (works on drafts too —
    // it creates another draft via copySurveyToOtherWorkspaceAction).
    await expect(page.getByTestId("duplicate-survey")).toBeVisible();
    await expect(page.getByText("Copy...", { exact: true })).toHaveCount(0);
    await expect(page.getByText("Preview", { exact: true })).toHaveCount(0);
    await expect(page.getByTestId("copy-link")).toHaveCount(0);
    await page.getByRole("button", { name: "Delete", exact: true }).click();
    await page.getByRole("dialog").getByRole("button", { name: "Delete", exact: true }).click();

    await deleteStarted;
    await expect(page.getByText(surveyName, { exact: true })).toBeHidden();
    await expect(page.getByText("Start from scratch", { exact: true })).toBeVisible();

    releaseDeleteRequest?.();
    await expect(page.getByText("Survey deleted successfully", { exact: true })).toBeVisible();
  });

  test("duplicating a survey from the list keeps its PIN", async ({ page, users }) => {
    const timestamp = Date.now();
    const email = `overview-duplicate-${timestamp}@example.com`;
    const name = `overview-duplicate-${timestamp}`;
    const surveyName = `Protected Survey ${timestamp}`;

    const user = await users.create({ email, name, workspaceName: "Duplicate Settings Workspace" });
    const userId = await getUserIdForEmail(email);

    await user.login();
    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);
    const workspaceId =
      /\/workspaces\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
      (() => {
        throw new Error("Unable to determine workspace id from surveys URL");
      })();

    // The field-by-field copy policy is unit-tested. This proves the list's Duplicate action reaches
    // the database with a setting intact — the PIN, whose loss mattered most (ENG-2144).
    await prisma.survey.create({
      data: { workspaceId, createdBy: userId, name: surveyName, status: "draft", type: "link", pin: "1234" },
    });

    await page.reload();
    await expect(page.getByText(surveyName, { exact: true })).toBeVisible({ timeout: 10000 });

    // Scoped to this survey's own actions menu — the workspace is seeded with another survey.
    const surveyActions = page.locator(`#${surveyName.toLowerCase().split(" ").join("-")}-survey-actions`);
    await surveyActions.getByTestId("survey-dropdown-trigger").click();
    await page.getByTestId("duplicate-survey").click();
    await expect(page.getByText("Survey duplicated successfully", { exact: true })).toBeVisible({
      timeout: 15000,
    });
    await expect(page.getByText(`${surveyName} (copy)`, { exact: true })).toBeVisible();

    const copy = await prisma.survey.findFirst({
      where: { workspaceId, name: `${surveyName} (copy)` },
      select: { pin: true },
    });
    expect(copy?.pin).toBe("1234");
  });

  test("restores the survey when delete fails", async ({ page, users }) => {
    const timestamp = Date.now();
    const email = `overview-delete-failure-${timestamp}@example.com`;
    const name = `overview-delete-failure-${timestamp}`;
    const surveyName = `Rollback Me ${timestamp}`;
    const user = await users.create({
      email,
      name,
      workspaceName: "Rollback Workspace",
    });

    const userId = await getUserIdForEmail(email);

    await user.login();
    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);
    const workspaceId =
      /\/workspaces\/([^/]+)\/surveys/.exec(page.url())?.[1] ??
      (() => {
        throw new Error("Unable to determine workspace id from surveys URL");
      })();
    const survey = await createSurveySeed({
      workspaceId,
      userId,
      name: surveyName,
      status: "draft",
      type: "link",
    });

    await prisma.survey.deleteMany({
      where: {
        workspaceId,
        id: {
          not: survey.id,
        },
      },
    });

    await page.reload();
    await expect(page.getByText(surveyName, { exact: true })).toBeVisible({ timeout: 10000 });

    await page.route(`**/api/v3/surveys/${survey.id}`, async (route) => {
      await new Promise((resolve) => setTimeout(resolve, 1000));
      await route.fulfill({
        status: 500,
        contentType: "application/problem+json",
        body: JSON.stringify({
          title: "Internal Server Error",
          status: 500,
          detail: "Delete failed",
          requestId: "playwright-delete-failure",
        }),
      });
    });

    await page.locator("[data-testid='survey-dropdown-trigger']").click();
    await page.getByRole("button", { name: "Delete", exact: true }).click();
    await page.getByRole("dialog").getByRole("button", { name: "Delete", exact: true }).click();

    await expect(page.getByText(surveyName, { exact: true })).toBeHidden();
    await expect(page.getByText(surveyName, { exact: true })).toBeVisible();
    await expect(page.getByText("Delete failed", { exact: true })).toBeVisible();
  });

  test("shows preview and copy link for published link surveys and only Export for a read-only app survey", async ({
    page,
    users,
  }) => {
    const timestamp = Date.now();
    const email = `overview-actions-${timestamp}@example.com`;
    const name = `overview-actions-${timestamp}`;
    const linkSurveyName = `Published Link ${timestamp}`;
    const appSurveyName = `Read Only App ${timestamp}`;
    const user = await users.create({
      email,
      name,
      workspaceName: "Action Workspace",
    });
    const { userId, organizationId, workspaceId } = await getWorkspaceIdsForEmail(email);

    await prisma.membership.update({
      where: {
        userId_organizationId: {
          userId,
          organizationId,
        },
      },
      data: {
        role: "member",
      },
    });

    const team = await prisma.team.create({
      data: {
        name: `Read Only Team ${timestamp}`,
        organizationId,
      },
      select: {
        id: true,
      },
    });

    await prisma.teamUser.create({
      data: {
        teamId: team.id,
        userId,
        role: "contributor",
      },
    });

    await prisma.workspaceTeam.create({
      data: {
        teamId: team.id,
        workspaceId,
        permission: "read",
      },
    });

    await user.login();
    await page.goto(`/workspaces/${workspaceId}/surveys`);

    await createSurveySeed({
      workspaceId,
      userId,
      name: linkSurveyName,
      status: "paused",
      type: "link",
    });
    await createSurveySeed({
      workspaceId,
      userId,
      name: appSurveyName,
      status: "completed",
      type: "app",
    });

    await page.reload();
    const linkRow = tableRow(page, "survey-list-table", linkSurveyName);
    await linkRow.locator("[data-testid='survey-dropdown-trigger']").click();
    await expect(page.getByRole("button", { name: "Preview", exact: true })).toBeVisible();
    await expect(page.getByTestId("copy-link")).toBeVisible();

    await page.keyboard.press("Escape");

    // Anyone who can see a survey can export it, so a read-only member's app survey row now has a menu
    // holding only Export.
    const appRow = tableRow(page, "survey-list-table", appSurveyName);
    await appRow.locator("[data-testid='survey-dropdown-trigger']").click();
    await expect(page.getByTestId("survey-export-submenu")).toBeVisible();
    await expect(page.getByTestId("copy-link")).toHaveCount(0);
  });
});
