import fs from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { sponsorPhoneIdentity } from "@/lib/sponsor-account";
import { normalizePhone } from "@/lib/utils";

const migrationPath = path.join(
  process.cwd(),
  "supabase",
  "migrations",
  "202607270002_sponsor_local_login.sql"
);
const importerPath = path.join(process.cwd(), "scripts", "import-sponsor-accounts.ts");
const authActionPath = path.join(process.cwd(), "src", "app", "actions", "auth.ts");
const proxyPath = path.join(process.cwd(), "src", "proxy.ts");

describe("international sponsor account identities", () => {
  it("derives exact local usernames for every supported country", () => {
    expect(sponsorPhoneIdentity("+249990006957")?.loginUsername).toBe("0990006957");
    expect(sponsorPhoneIdentity("+966562063561")?.loginUsername).toBe("0562063561");
    expect(sponsorPhoneIdentity("+971505541472")?.loginUsername).toBe("0505541472");
    expect(sponsorPhoneIdentity("+96894792843")?.loginUsername).toBe("094792843");
  });

  it("rejects invalid country-specific lengths without padding", () => {
    expect(sponsorPhoneIdentity("+97150651075")).toBeNull();
    expect(normalizePhone("966562063561")).toBe("+966562063561");
    expect(normalizePhone("971505541472")).toBe("+971505541472");
    expect(normalizePhone("96894792843")).toBe("+96894792843");
  });
});

describe("bulk sponsor import safety", () => {
  it("adds unique usernames and first-login state through a transaction", async () => {
    const sql = (await fs.readFile(migrationPath, "utf8")).toLowerCase();

    expect(sql).toContain("begin;");
    expect(sql).toContain("commit;");
    expect(sql).toContain("login_username");
    expect(sql).toContain("must_change_password");
    expect(sql).toContain("profiles_login_username_unique");
    expect(sql).toContain("sponsor login username does not match the auth phone");
  });

  it("uses confirmed phone Auth users, prechecks duplicates, and rolls back failed profiles", async () => {
    const importer = await fs.readFile(importerPath, "utf8");

    expect(importer).toContain("auth.admin.listUsers");
    expect(importer).toContain("phone_confirm: true");
    expect(importer).toContain("must_change_password: true");
    expect(importer).toContain("profilePhones.has(account.phone)");
    expect(importer).toContain("profileUsernames.has(account.loginUsername)");
    expect(importer).toContain("auth.admin.deleteUser(userId)");
    expect(importer).not.toContain("console.log(account.loginUsername)");
    expect(importer).not.toContain("console.log(account.suppliedUsername)");
  });

  it("maps local usernames server-side and blocks donor pages until the password changes", async () => {
    const [authAction, proxy] = await Promise.all([
      fs.readFile(authActionPath, "utf8"),
      fs.readFile(proxyPath, "utf8")
    ]);

    expect(authAction).toContain('.eq("login_username", parsed.data.identifier.value)');
    expect(authAction).toContain("currentProfile.login_username === password");
    expect(authAction).toContain(".update({ must_change_password: false })");
    expect(authAction).toContain('"/donor/security?required=1"');
    expect(proxy).toContain("profile.must_change_password");
    expect(proxy).toContain('destination.pathname = "/donor/security"');
  });
});
