import { beforeEach, describe, expect, test, vi } from "vitest";
import { logger } from "@formbricks/logger";
import { TOrganizationBilling } from "@formbricks/types/organizations";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getOrganizationBillingByWorkspaceId } from "@/app/api/v2/client/[workspaceId]/responses/lib/organization";
import { verifyRecaptchaToken } from "@/app/api/v2/client/[workspaceId]/responses/lib/recaptcha";
import { checkSurveyValidity } from "@/app/api/v2/client/[workspaceId]/responses/lib/utils";
import { TResponseInputV2 } from "@/app/api/v2/client/[workspaceId]/responses/types/response";
import { responses } from "@/app/lib/api/response";
import { symmetricDecrypt } from "@/lib/crypto";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { generateSurveySingleUseSignature } from "@/lib/utils/single-use-surveys";
import { getIsSpamProtectionEnabled } from "@/modules/ee/license-check/lib/utils";

vi.mock("@/lib/i18n/utils", () => ({
  getLocalizedValue: vi.fn().mockImplementation((value, language) => {
    return typeof value === "string" ? value : value[language] || value["default"] || "";
  }),
}));

vi.mock("@/app/api/v2/client/[workspaceId]/responses/lib/recaptcha", () => ({
  verifyRecaptchaToken: vi.fn(),
}));

vi.mock("@/app/lib/api/response", () => ({
  responses: {
    badRequestResponse: vi.fn((message) => new Response(message, { status: 400 })),
    notFoundResponse: vi.fn((message) => new Response(message, { status: 404 })),
    forbiddenResponse: vi.fn((message) => new Response(message, { status: 403 })),
  },
}));

vi.mock("@/modules/ee/license-check/lib/utils", () => ({
  getIsSpamProtectionEnabled: vi.fn(),
}));

vi.mock("@/app/api/v2/client/[workspaceId]/responses/lib/organization", () => ({
  getOrganizationBillingByWorkspaceId: vi.fn(),
}));

vi.mock("@/lib/utils/helper", () => ({
  getOrganizationIdFromWorkspaceId: vi.fn(),
}));

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

// Stub only `symmetricDecrypt`. The rest of the module stays real because the single-use signature
// check on this path runs through `constantTimeEqual` — stubbing it out would reject valid signatures.
vi.mock("@/lib/crypto", async (importOriginal: () => Promise<typeof import("@/lib/crypto")>) => ({
  ...(await importOriginal()),
  symmetricDecrypt: vi.fn(),
}));
vi.mock("@/lib/constants", () => ({
  ENCRYPTION_KEY: "test-key",
}));
vi.mock("@/lib/env", () => ({
  env: {
    ENCRYPTION_KEY: "test-key",
  },
}));

const mockSurvey: TSurvey = {
  id: "survey-1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Test Survey",
  type: "link",
  workspaceId: "ws-1",
  status: "inProgress",
  visibility: "workspace",
  ownerId: null,
  visibilityVersion: 0,
  visibilityProjectedVersion: 0,
  visibilityChangedAt: null,
  visibilityChangedById: null,
  questions: [],
  displayOption: "displayOnce",
  recontactDays: null,
  autoClose: null,
  delay: 0,
  displayPercentage: null,
  autoComplete: null,
  singleUse: null,
  triggers: [],
  languages: [],
  pin: null,
  segment: null,
  styling: null,
  surveyClosedMessage: null,
  hiddenFields: { enabled: false },
  welcomeCard: { enabled: false, showResponseCount: false, timeToFinish: false },
  variables: [],
  createdBy: null,
  recaptcha: { enabled: false, threshold: 0.5 },
  displayLimit: null,
  endings: [],
  followUps: [],
  isBackButtonHidden: false,
  isVerifyEmailEnabled: false,
  workspaceOverwrites: null,
  showLanguageSwitch: false,
  blocks: [],
  isCaptureIpEnabled: false,
  isAnonymizeResponsesEnabled: false,
  isAutoProgressingEnabled: true,
  publishOn: null,
  closeOn: null,
  metadata: {},
  slug: null,
};

const mockResponseInput: TResponseInputV2 = {
  surveyId: "survey-1",
  workspaceId: "ws-1",
  data: {},
  finished: false,
  ttc: {},
  meta: {},
};

const mockBillingData: TOrganizationBilling = {
  limits: {
    monthly: { responses: 0 },
    workspaces: 3,
  },
  usageCycleAnchor: new Date(),
  stripeCustomerId: "mock-stripe-customer-id",
};
const validSingleUseId = "cm8f4x9mm0001gx9h5b7d7h3q";

describe("checkSurveyValidity", () => {
  beforeEach(() => {
    vi.resetAllMocks();
    vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValue("cm8f4x9mm0001gx9h5b7d7h3q");
  });

  test("should return badRequestResponse if survey workspaceId does not match", async () => {
    const survey = { ...mockSurvey, workspaceId: "ws-2" };
    const result = await checkSurveyValidity(survey, "ws-1", mockResponseInput);
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith(
      "Survey is part of another workspace",
      {
        workspaceId: "ws-1",
      },
      true
    );
  });

  test.each(["draft", "paused", "completed"] as const)(
    "should return forbiddenResponse when survey status is %s",
    async (status) => {
      const survey = { ...mockSurvey, status } as TSurvey;
      const result = await checkSurveyValidity(survey, "ws-1", mockResponseInput);
      expect(result).toBeInstanceOf(Response);
      expect(result?.status).toBe(403);
      expect(responses.forbiddenResponse).toHaveBeenCalledWith("Survey is not accepting submissions", true, {
        surveyId: mockSurvey.id,
      });
    }
  );

  test("should return null if recaptcha is not enabled", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: false, threshold: 0.5 }, workspaceId: "ws-1" };
    const result = await checkSurveyValidity(survey, "ws-1", mockResponseInput);
    expect(result).toBeNull();
  });

  test("should return badRequestResponse if recaptcha enabled, spam protection enabled, but token is missing", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: true, threshold: 0.5 }, workspaceId: "ws-1" };
    vi.mocked(getIsSpamProtectionEnabled).mockResolvedValue(true);
    const responseInputWithoutToken = { ...mockResponseInput };
    delete responseInputWithoutToken.recaptchaToken;

    const result = await checkSurveyValidity(survey, "ws-1", responseInputWithoutToken);
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    // warn, not error: a missing token on a public endpoint is caller-controlled, not a fault.
    expect(logger.warn).toHaveBeenCalledWith("Missing recaptcha token");
    expect(responses.badRequestResponse).toHaveBeenCalledWith(
      "Missing recaptcha token",
      { code: "recaptcha_verification_failed" },
      true
    );
  });

  test("should return not found response if billing data is not found", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: true, threshold: 0.5 }, workspaceId: "ws-1" };
    vi.mocked(getIsSpamProtectionEnabled).mockResolvedValue(true);
    vi.mocked(getOrganizationBillingByWorkspaceId).mockResolvedValue(null);

    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      recaptchaToken: "test-token",
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(404);
    // cors: true, matching every other response this path returns.
    expect(responses.notFoundResponse).toHaveBeenCalledWith("Organization", null, true);
    expect(getOrganizationBillingByWorkspaceId).toHaveBeenCalledWith("ws-1");
  });

  test("should return null if recaptcha is enabled but spam protection is disabled", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: true, threshold: 0.5 }, workspaceId: "ws-1" };
    vi.mocked(getIsSpamProtectionEnabled).mockResolvedValue(false);
    vi.mocked(verifyRecaptchaToken).mockResolvedValue(true);
    vi.mocked(getOrganizationBillingByWorkspaceId).mockResolvedValue(mockBillingData);
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      recaptchaToken: "test-token",
    });
    expect(result).toBeNull();
    expect(logger.warn).toHaveBeenCalledWith("Spam protection is not enabled for this organization");
  });

  test("should return badRequestResponse if recaptcha verification fails", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: true, threshold: 0.5 }, workspaceId: "ws-1" };
    const responseInputWithToken = { ...mockResponseInput, recaptchaToken: "test-token" };
    vi.mocked(getIsSpamProtectionEnabled).mockResolvedValue(true);
    vi.mocked(verifyRecaptchaToken).mockResolvedValue(false);
    vi.mocked(getOrganizationBillingByWorkspaceId).mockResolvedValue(mockBillingData);

    const result = await checkSurveyValidity(survey, "ws-1", responseInputWithToken);
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(verifyRecaptchaToken).toHaveBeenCalledWith("test-token", 0.5);
    expect(responses.badRequestResponse).toHaveBeenCalledWith(
      "reCAPTCHA verification failed",
      { code: "recaptcha_verification_failed" },
      true
    );
  });

  test("should return null if recaptcha verification passes", async () => {
    const survey = { ...mockSurvey, recaptcha: { enabled: true, threshold: 0.5 }, workspaceId: "ws-1" };
    const responseInputWithToken = { ...mockResponseInput, recaptchaToken: "test-token" };
    vi.mocked(getIsSpamProtectionEnabled).mockResolvedValue(true);
    vi.mocked(verifyRecaptchaToken).mockResolvedValue(true);
    vi.mocked(getOrganizationBillingByWorkspaceId).mockResolvedValue(mockBillingData);

    const result = await checkSurveyValidity(survey, "ws-1", responseInputWithToken);
    expect(result).toBeNull();
    expect(verifyRecaptchaToken).toHaveBeenCalledWith("test-token", 0.5);
  });

  test("should return null for a valid survey and input", async () => {
    const survey = { ...mockSurvey, workspaceId: "ws-1" }; // Recaptcha disabled by default in mock
    const result = await checkSurveyValidity(survey, "ws-1", mockResponseInput);
    expect(result).toBeNull();
  });

  test("should return badRequestResponse if singleUse is enabled and singleUseId is missing", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const result = await checkSurveyValidity(survey, "ws-1", { ...mockResponseInput });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Missing single use id", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return badRequestResponse if singleUse is enabled and meta.url is missing", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: {},
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Missing or invalid URL in response metadata", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return badRequestResponse if meta.url is invalid", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url: "not-a-url" },
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith(
      "Invalid URL in response metadata",
      expect.objectContaining({ surveyId: survey.id, workspaceId: "ws-1" })
    );
  });

  test("should return badRequestResponse if suId is missing from url", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const url = "https://example.com/?foo=bar";
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url },
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Missing single use id", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return badRequestResponse if isEncrypted and decrypted suId does not match singleUseId", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: true }, workspaceId: "ws-1" };
    // Signed for this survey, so validation reaches the decrypt-and-compare step instead of
    // short-circuiting at the binding check (ENG-2758).
    const suToken = generateSurveySingleUseSignature(mockSurvey.id, "encrypted-id");
    const url = `https://example.com/?suId=encrypted-id&suToken=${suToken}`;
    vi.mocked(symmetricDecrypt).mockReturnValue("decrypted-id");
    const resultEncryptedMismatch = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url },
    });
    expect(symmetricDecrypt).toHaveBeenCalledWith("encrypted-id", "test-key");
    expect(resultEncryptedMismatch).toBeInstanceOf(Response);
    expect(resultEncryptedMismatch?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Invalid single use id", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return badRequestResponse if not encrypted and suId does not match singleUseId", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const url = "https://example.com/?suId=su-2";
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url },
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Invalid single use id", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return badRequestResponse if singleUse is enabled, not encrypted, and suId present but no suToken", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const url = "https://example.com/?suId=su-1";
    const result = await checkSurveyValidity(survey, "ws-1", {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url },
    });
    expect(result).toBeInstanceOf(Response);
    expect(result?.status).toBe(400);
    expect(responses.badRequestResponse).toHaveBeenCalledWith("Invalid single use id", {
      surveyId: survey.id,
      workspaceId: "ws-1",
    });
  });

  test("should return null if singleUse is enabled, not encrypted, and signed suId matches singleUseId", async () => {
    const survey = { ...mockSurvey, singleUse: { enabled: true, isEncrypted: false }, workspaceId: "ws-1" };
    const suToken = generateSurveySingleUseSignature(survey.id, "su-1");
    const url = `https://example.com/?suId=su-1&suToken=${suToken}`;
    const responseInput = {
      ...mockResponseInput,
      singleUseId: "su-1",
      meta: { url },
    };
    const result = await checkSurveyValidity(survey, "ws-1", responseInput);
    expect(result).toBeNull();
    expect(responseInput.singleUseId).toBe("su-1");
  });

  describe("encrypted single-use links are bound to their survey (ENG-2758)", () => {
    const encryptedSurvey = () => ({
      ...mockSurvey,
      singleUse: { enabled: true, isEncrypted: true },
      workspaceId: "ws-1",
    });
    const urlFor = (suToken?: string) =>
      `https://example.com/?suId=encrypted-id${suToken ? `&suToken=${suToken}` : ""}`;

    test("rejects an encrypted suId that carries no binding token, without decrypting it", async () => {
      // This assertion used to be the opposite: the gate accepted a tokenless encrypted suId, which
      // is the vulnerability -- nothing tied the ciphertext to this survey.
      vi.mocked(symmetricDecrypt).mockReturnValue(validSingleUseId);

      const result = await checkSurveyValidity(encryptedSurvey(), "ws-1", {
        ...mockResponseInput,
        singleUseId: validSingleUseId,
        meta: { url: urlFor() },
      });

      expect(result?.status).toBe(400);
      expect(symmetricDecrypt).not.toHaveBeenCalled();
    });

    test("rejects an encrypted suId whose token is bound to a different survey", async () => {
      // Minted on the attacker's own survey and replayed here. One shared ENCRYPTION_KEY means the
      // ciphertext decrypts fine; only the HMAC tells the two surveys apart.
      vi.mocked(symmetricDecrypt).mockReturnValue(validSingleUseId);

      const result = await checkSurveyValidity(encryptedSurvey(), "ws-1", {
        ...mockResponseInput,
        singleUseId: validSingleUseId,
        meta: { url: urlFor(generateSurveySingleUseSignature("cm0attacker00000000000001", "encrypted-id")) },
      });

      expect(result?.status).toBe(400);
      expect(responses.badRequestResponse).toHaveBeenCalledWith("Invalid single use id", {
        surveyId: mockSurvey.id,
        workspaceId: "ws-1",
      });
    });

    test("accepts an encrypted suId bound to this survey, and canonicalises it", async () => {
      vi.mocked(symmetricDecrypt).mockReturnValue(validSingleUseId);
      const responseInput = {
        ...mockResponseInput,
        singleUseId: validSingleUseId,
        meta: { url: urlFor(generateSurveySingleUseSignature(mockSurvey.id, "encrypted-id")) },
      };

      expect(await checkSurveyValidity(encryptedSurvey(), "ws-1", responseInput)).toBeNull();
      expect(symmetricDecrypt).toHaveBeenCalledWith("encrypted-id", "test-key");
      expect(responseInput.singleUseId).toBe(validSingleUseId);
    });
  });
});
