import { beforeEach, describe, expect, test, vi } from "vitest";
import { logger } from "@formbricks/logger";
import { findWorkspaceByIdOrLegacyEnvId } from "@/lib/utils/resolve-client-id";
import { deleteFile } from "@/modules/storage/service";
import { deleteResponseFileUrls } from "./delete-response-files";

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

vi.mock("server-only", () => ({}));

// Only reached by the test that runs the real `deleteFile`; every other test stubs that function itself.
vi.mock("@formbricks/storage", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@formbricks/storage")>()),
  deleteFile: mockDeleteFromS3,
}));

vi.mock("@formbricks/logger", () => ({
  logger: {
    error: vi.fn(),
  },
}));

vi.mock("@/lib/utils/resolve-client-id", () => ({
  findWorkspaceByIdOrLegacyEnvId: vi.fn(),
}));

vi.mock("@/modules/storage/service", () => ({
  deleteFile: vi.fn(),
}));

const mockedResolve = vi.mocked(findWorkspaceByIdOrLegacyEnvId);
const mockedDeleteFile = vi.mocked(deleteFile);

const OWN_WORKSPACE = "ws-own";
const FOREIGN_WORKSPACE = "ws-victim";

describe("deleteResponseFileUrls", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedDeleteFile.mockResolvedValue({ ok: true, data: undefined });
  });

  test("deletes a file whose URL storage id belongs to the survey's workspace", async () => {
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });

    await deleteResponseFileUrls([`/storage/${OWN_WORKSPACE}/private/answer.png`], OWN_WORKSPACE);

    expect(mockedDeleteFile).toHaveBeenCalledTimes(1);
    expect(mockedDeleteFile).toHaveBeenCalledWith(OWN_WORKSPACE, "private", "answer.png", OWN_WORKSPACE);
  });

  // The core cross-tenant guard: a planted URL pointing into another tenant's storage prefix must not be
  // deleted, even though it survived write-time validation via the element-id flip TOCTOU.
  test("refuses to delete a planted URL that resolves to a different workspace", async () => {
    mockedResolve.mockResolvedValue({ id: FOREIGN_WORKSPACE, organizationId: "org-2" });

    await deleteResponseFileUrls([`/storage/${FOREIGN_WORKSPACE}/public/bg--fid--uuid.png`], OWN_WORKSPACE);

    expect(mockedDeleteFile).not.toHaveBeenCalled();
  });

  // Legacy uploads were prefixed with the environment id; the resolver maps that back to the owning
  // workspace, so a same-workspace legacy prefix is still deletable — using its real (legacy) prefix.
  test("allows a legacy environment-id prefix that maps back to the survey's workspace", async () => {
    const legacyEnvId = "env-legacy";
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });

    await deleteResponseFileUrls([`/storage/${legacyEnvId}/private/old.png`], OWN_WORKSPACE);

    expect(mockedResolve).toHaveBeenCalledWith(legacyEnvId);
    expect(mockedDeleteFile).toHaveBeenCalledWith(legacyEnvId, "private", "old.png", OWN_WORKSPACE);
  });

  test("refuses when the storage id resolves to no workspace", async () => {
    mockedResolve.mockResolvedValue(null);

    await deleteResponseFileUrls(["/storage/ws-unknown/public/x.png"], OWN_WORKSPACE);

    expect(mockedDeleteFile).not.toHaveBeenCalled();
  });

  test("deletes nothing and never resolves when no survey workspace id is given", async () => {
    await deleteResponseFileUrls([`/storage/${OWN_WORKSPACE}/private/answer.png`], undefined);

    expect(mockedResolve).not.toHaveBeenCalled();
    expect(mockedDeleteFile).not.toHaveBeenCalled();
  });

  test("skips an unparseable URL without throwing", async () => {
    await deleteResponseFileUrls(["not-a-storage-url"], OWN_WORKSPACE);

    expect(mockedResolve).not.toHaveBeenCalled();
    expect(mockedDeleteFile).not.toHaveBeenCalled();
  });

  test("in a mixed batch, deletes the owned file and refuses the foreign one", async () => {
    mockedResolve.mockImplementation(async (id: string) =>
      id === OWN_WORKSPACE
        ? { id: OWN_WORKSPACE, organizationId: "org-1" }
        : { id: id, organizationId: "org-2" }
    );

    await deleteResponseFileUrls(
      [`/storage/${OWN_WORKSPACE}/private/mine.png`, `/storage/${FOREIGN_WORKSPACE}/public/theirs.png`],
      OWN_WORKSPACE
    );

    expect(mockedDeleteFile).toHaveBeenCalledTimes(1);
    expect(mockedDeleteFile).toHaveBeenCalledWith(OWN_WORKSPACE, "private", "mine.png", OWN_WORKSPACE);
  });

  // deleteFile returns an error result instead of throwing, so a failed storage deletion must still be
  // logged — otherwise a leftover object looks like a clean success.
  test("logs when deleteFile returns a failure result", async () => {
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });
    mockedDeleteFile.mockResolvedValue({ ok: false, error: { code: "s3_client_error" } } as Awaited<
      ReturnType<typeof mockedDeleteFile>
    >);

    await deleteResponseFileUrls([`/storage/${OWN_WORKSPACE}/private/answer.png`], OWN_WORKSPACE);

    expect(mockedDeleteFile).toHaveBeenCalledTimes(1);
    expect(logger.error).toHaveBeenCalledWith(
      expect.objectContaining({ error: { code: "s3_client_error" } }),
      "Failed to delete a response file from storage"
    );
  });

  test("resolves each distinct storage id only once for multiple files under it", async () => {
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });

    await deleteResponseFileUrls(
      [`/storage/${OWN_WORKSPACE}/private/one.png`, `/storage/${OWN_WORKSPACE}/private/two.png`],
      OWN_WORKSPACE
    );

    expect(mockedResolve).toHaveBeenCalledTimes(1);
    expect(mockedDeleteFile).toHaveBeenCalledTimes(2);
  });

  // The URL carries a percent-encoded file name but the object is stored under the decoded name, so the
  // helper must decode before building the S3 key, or files with spaces/non-ASCII names never delete.
  test("decodes the percent-encoded file name before deleting", async () => {
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });

    await deleteResponseFileUrls([`/storage/${OWN_WORKSPACE}/private/my%20file%20(1).png`], OWN_WORKSPACE);

    expect(mockedDeleteFile).toHaveBeenCalledWith(OWN_WORKSPACE, "private", "my file (1).png", OWN_WORKSPACE);
  });

  // Decoded, this is `surveys//svy-other/…`: it names no survey, so collection reads it as a flat key.
  // Only the real `deleteFile` keeps it from storage, where a backend that merges `//` would read it as
  // another survey's object.
  test("never sends an encoded empty-segment key to storage", async () => {
    const { deleteFile: realDeleteFile } =
      await vi.importActual<typeof import("@/modules/storage/service")>("@/modules/storage/service");
    mockedResolve.mockResolvedValue({ id: OWN_WORKSPACE, organizationId: "org-1" });
    mockedDeleteFile.mockImplementation(realDeleteFile);
    mockDeleteFromS3.mockResolvedValue({ ok: true, data: undefined });

    await deleteResponseFileUrls(
      [`/storage/${OWN_WORKSPACE}/private/surveys%2F%2Fsvy-other%2Felements%2Fe%2Ff`],
      OWN_WORKSPACE
    );

    expect(mockedDeleteFile).toHaveBeenCalledWith(
      OWN_WORKSPACE,
      "private",
      "surveys//svy-other/elements/e/f",
      OWN_WORKSPACE
    );
    expect(mockDeleteFromS3).not.toHaveBeenCalled();
  });

  // ENG-3612: the cleanup drain retries what this reports, so only a failure that can change on retry
  // may be reported: a refusal reported as failed would be retried forever.
  describe("reports which deletes are worth retrying", () => {
    const own = (name: string) => `/storage/${OWN_WORKSPACE}/private/${name}`;

    beforeEach(() => {
      mockedResolve.mockImplementation(async (id: string) => ({ id, organizationId: "org-1" }));
    });

    test("reports storage errors and a throw, but not success, not-found or a refused key", async () => {
      mockedDeleteFile.mockImplementation((async (_id: string, _access: string, fileName: string) => {
        if (fileName === "s3-down.png") return { ok: false, error: { code: "s3_client_error" } };
        if (fileName === "throws.png") throw new Error("socket hang up");
        if (fileName === "gone.png") return { ok: false, error: { code: "file_not_found_error" } };
        if (fileName === "refused.png") return { ok: false, error: { code: "invalid_input" } };
        return { ok: true, data: undefined };
      }) as never);

      const result = await deleteResponseFileUrls(
        ["ok.png", "s3-down.png", "throws.png", "gone.png", "refused.png"].map(own),
        OWN_WORKSPACE
      );

      expect(result.failed.sort()).toEqual([own("s3-down.png"), own("throws.png")].sort());
    });

    test("never reports a foreign, unparseable or malformed URL", async () => {
      mockedResolve.mockResolvedValue({ id: FOREIGN_WORKSPACE, organizationId: "org-2" });

      const result = await deleteResponseFileUrls(
        [`/storage/${FOREIGN_WORKSPACE}/private/theirs.png`, "not-a-storage-url", own("bad%E0%A4%A.png")],
        OWN_WORKSPACE
      );

      expect(result.failed).toEqual([]);
      expect(mockedDeleteFile).not.toHaveBeenCalled();
    });

    test("reports a failed workspace lookup, which can succeed on retry", async () => {
      mockedResolve.mockRejectedValue(new Error("db down"));

      const result = await deleteResponseFileUrls([own("a.png")], OWN_WORKSPACE);

      expect(result.failed).toEqual([own("a.png")]);
    });
  });

  // ENG-3721: a response file URL carries the file name the respondent chose, which can be personal data.
  test("never logs a file name, whatever the outcome", async () => {
    const secret = "passport_jane_doe.pdf";
    mockedResolve.mockImplementation(async (id: string) =>
      id === OWN_WORKSPACE ? { id, organizationId: "org-1" } : { id, organizationId: "org-2" }
    );
    mockedDeleteFile.mockImplementation(async () => {
      throw new Error("socket hang up");
    });
    mockedDeleteFile.mockResolvedValueOnce({ ok: false, error: { code: "s3_client_error" } } as never);

    await deleteResponseFileUrls(
      [
        `/storage/${OWN_WORKSPACE}/private/${secret}`,
        `/storage/${OWN_WORKSPACE}/private/2-${secret}`,
        `/storage/${FOREIGN_WORKSPACE}/private/${secret}`,
        `/storage/${OWN_WORKSPACE}/private/bad%E0%A4%A${secret}`,
        `not-a-storage-url-${secret}`,
      ],
      OWN_WORKSPACE
    );

    expect(vi.mocked(logger.error).mock.calls.length).toBeGreaterThanOrEqual(4);
    expect(JSON.stringify(vi.mocked(logger.error).mock.calls)).not.toContain("jane_doe");
  });
});
