import { beforeEach, describe, expect, test } from "vitest";
import { prisma } from "@formbricks/database";
import { resetDb } from "@/integration/reset-db";
import { hashSecret } from "@/lib/crypto";
import { auth } from "@/modules/auth/lib/auth";
import { canonicalAccountIssuer } from "@/modules/ee/sso/lib/constants";
// The cutover data migration under test (auto-discovered by the migration runner at the flip).
import { backfillCredentialAccounts } from "../../../packages/database/migration/20260619120000_eng_1054_credential_account_backfill/migration";

/**
 * This migration predates `Account.issuer` (ENG-2343) and, by the runner's own interleaving guarantee
 * (data and schema migrations run in strict timestamp order), always runs BEFORE the schema migration
 * that adds that column — so it genuinely cannot set it, and its rows are inserted with issuer=NULL.
 * In real deployments that's fine: ENG-2343's schema migration runs immediately after this one and
 * backfills every NULL-issuer row. A test calling this function standalone has to simulate that
 * follow-up step itself before asserting a real Better Auth sign-in succeeds — using the same canonical
 * mapping production uses, so the fixture cannot drift from it (ENG-2555).
 */
const applyEng2343IssuerBackfill = async (): Promise<void> => {
  const rows = await prisma.account.findMany({
    where: { issuer: null },
    select: { id: true, provider: true },
  });

  // Per row, because the real backfill is a CASE over `provider` — a single `updateMany` could only
  // reproduce one arm of it. An earlier version of this helper did exactly that (credential only), which
  // left the google row below at issuer=NULL and quietly diverged from what production data looks like.
  await Promise.all(
    rows.map((row) =>
      prisma.account.update({
        where: { id: row.id },
        data: { issuer: canonicalAccountIssuer(row.provider) },
      })
    )
  );
};

/**
 * Integration coverage for the cutover credential-account backfill (ENG-1054) against real Postgres.
 * Proves the scariest cutover guarantee: an existing NextAuth-era user (bcrypt hash on User.password,
 * NO credential Account) can sign in via Better Auth after the backfill — no re-hash, no forced reset.
 */
beforeEach(async () => {
  await resetDb();
});

describe("Credential-account backfill (real Postgres)", () => {
  test("an existing User.password user can sign in via Better Auth after the backfill", async () => {
    const password = "LegacyPassw0rd!";
    const user = await prisma.user.create({
      data: {
        email: "legacy@example.com",
        name: "Legacy",
        emailVerified: true,
        password: await hashSecret(password),
      },
    });
    // NextAuth-era state: the hash lives on User.password, with no Account rows yet
    expect(await prisma.account.count({ where: { userId: user.id } })).toBe(0);

    const stats = await backfillCredentialAccounts(prisma);
    expect(stats.inserted).toBe(1);

    // a credential Account now exists in the shape BA reads, with the hash copied verbatim (no re-hash)
    const account = await prisma.account.findUnique({
      where: { provider_providerAccountId: { provider: "credential", providerAccountId: user.id } },
    });
    expect(account?.userId).toBe(user.id);
    expect(account?.password).toBe(user.password);

    await applyEng2343IssuerBackfill();

    // and BA email/password sign-in works with the ORIGINAL password
    const res = await auth.api.signInEmail({
      body: { email: "legacy@example.com", password },
      asResponse: true,
    });
    expect(res.status).toBe(200);
  });

  test("is idempotent: running twice keeps a single credential account", async () => {
    const user = await prisma.user.create({
      data: {
        email: "legacy2@example.com",
        name: "Legacy2",
        emailVerified: true,
        password: await hashSecret("X1y2z3Ab!"),
      },
    });

    await backfillCredentialAccounts(prisma);
    const second = await backfillCredentialAccounts(prisma);

    expect(second.inserted).toBe(0);
    expect(second.skippedExisting).toBe(1);
    expect(await prisma.account.count({ where: { userId: user.id, provider: "credential" } })).toBe(1);
  });

  test("skips users without a password (no credential account inserted)", async () => {
    const user = await prisma.user.create({
      data: { email: "nopw@example.com", name: "NoPw", emailVerified: true }, // SSO-only user, no password
    });

    const stats = await backfillCredentialAccounts(prisma);

    expect(stats.inserted).toBe(0);
    expect(await prisma.account.count({ where: { userId: user.id } })).toBe(0);
  });

  test("does not clobber an existing credential account (ON CONFLICT DO NOTHING)", async () => {
    const user = await prisma.user.create({
      data: {
        email: "exists@example.com",
        name: "Exists",
        emailVerified: true,
        password: await hashSecret("RealPw1!"),
      },
    });
    // a pre-existing credential account holding a DIFFERENT (sentinel) password
    await prisma.account.create({
      data: {
        userId: user.id,
        type: "credential",
        provider: "credential",
        providerAccountId: user.id,
        password: "SENTINEL-DO-NOT-CLOBBER",
      },
    });

    const stats = await backfillCredentialAccounts(prisma);
    expect(stats.inserted).toBe(0);
    expect(stats.skippedExisting).toBe(1);

    const account = await prisma.account.findUnique({
      where: { provider_providerAccountId: { provider: "credential", providerAccountId: user.id } },
    });
    expect(account?.password).toBe("SENTINEL-DO-NOT-CLOBBER"); // untouched
  });

  test("a user with both a password and an SSO account gets a credential account and can sign in", async () => {
    const password = "BothAuth1!";
    const user = await prisma.user.create({
      data: {
        email: "both@example.com",
        name: "Both",
        emailVerified: true,
        password: await hashSecret(password),
      },
    });
    // a pre-existing SSO (google) account, as the legacy-SSO backfill would have created
    await prisma.account.create({
      data: { userId: user.id, type: "oauth", provider: "google", providerAccountId: "google-sub-123" },
    });

    const stats = await backfillCredentialAccounts(prisma);
    expect(stats.inserted).toBe(1);

    await applyEng2343IssuerBackfill();

    // both the SSO and the new credential account coexist, and password sign-in works
    expect(await prisma.account.count({ where: { userId: user.id } })).toBe(2);
    const res = await auth.api.signInEmail({
      body: { email: "both@example.com", password },
      asResponse: true,
    });
    expect(res.status).toBe(200);
  });
});
