/**
 * Account security tests (run: npm test): two-factor methods, code handling, backup codes, lockout, trusted devices,
 * IP allowlists and origin checks. In-memory Postgres seeded with the demo workspace.
 */
process.env.PGLITE_DIR = "memory";
process.env.SEED_DEMO = "true";
process.env.PASSWORD_BREACH_CHECK = "false"; // no network in tests

import { test, before } from "node:test";
import assert from "node:assert/strict";
import { eq } from "drizzle-orm";
import { getDb, schema, type DB } from "../src/db";
import { totp } from "../src/lib/crypto";

let db: DB;
let user: typeof schema.users.$inferSelect;

before(async () => {
  db = await getDb();
  user = (await db.query.users.findFirst({ where: eq(schema.users.email, "admin@brandtempest.com") }))!;
  assert.ok(user, "demo admin seeded");
});

test("ADM-002: authenticator app — secret encrypted at rest, codes verify once (replay blocked)", async () => {
  const { startTotp, checkTotp, refreshMfaFlag } = await import("../src/lib/security/mfa");
  const { method, secret } = await startTotp(db, user.id, "Test phone");
  assert.ok(method.secretEnc && !method.secretEnc.includes(secret), "secret is not stored in plaintext");
  const code = totp(secret);
  assert.equal(await checkTotp(db, method, "000000" === code ? "111111" : "000000"), false);
  assert.equal(await checkTotp(db, method, code), true);
  const fresh = (await db.query.mfaMethods.findFirst({ where: eq(schema.mfaMethods.id, method.id) }))!;
  assert.equal(await checkTotp(db, fresh, code), false, "same code can't be replayed");
  await db.update(schema.mfaMethods).set({ verifiedAt: new Date() }).where(eq(schema.mfaMethods.id, method.id));
  assert.equal(await refreshMfaFlag(db, user.id), true);
  await db.delete(schema.mfaMethods).where(eq(schema.mfaMethods.userId, user.id));
  await refreshMfaFlag(db, user.id);
});

test("ADM-002: legacy plaintext MFA secrets are migrated into encrypted methods", async () => {
  const { userMethods } = await import("../src/lib/security/mfa");
  await db.update(schema.users).set({ mfaSecret: "JBSWY3DPEHPK3PXP", mfaEnabled: true }).where(eq(schema.users.id, user.id));
  const u = (await db.query.users.findFirst({ where: eq(schema.users.id, user.id) }))!;
  const ms = await userMethods(db, u);
  assert.equal(ms.length, 1);
  assert.equal(ms[0]!.type, "totp");
  assert.equal((await db.query.users.findFirst({ where: eq(schema.users.id, user.id) }))!.mfaSecret, null);
  await db.delete(schema.mfaMethods).where(eq(schema.mfaMethods.userId, user.id));
  await db.update(schema.users).set({ mfaEnabled: false }).where(eq(schema.users.id, user.id));
});

test("ADM-002: email & SMS codes — delivered, hashed, single use, 5 attempts, resend cool-down", async () => {
  const { sendCode, verifyCode } = await import("../src/lib/security/mfa");
  const logged: string[] = [];
  const orig = console.info;
  console.info = (...a: unknown[]) => { logged.push(a.join(" ")); };
  try {
    const [sms] = await db.insert(schema.mfaMethods).values({ userId: user.id, type: "sms", target: "+8801712000111", verifiedAt: new Date() }).returning();
    const r = await sendCode(db, user, sms!, "login");
    const code = logged.join("\n").match(/\b(\d{6})\b/)![1]!;
    const row = (await db.query.mfaChallenges.findFirst({ where: eq(schema.mfaChallenges.id, r.challengeId) }))!;
    assert.ok(row.codeHash && !row.codeHash.includes(code), "only a keyed hash is stored");
    await assert.rejects(() => sendCode(db, user, sms!, "login"), /wait/i, "resend cool-down");
    await assert.rejects(() => verifyCode(db, user.id, r.challengeId, code === "123456" ? "654321" : "123456", sms!.id), /not valid/);
    await verifyCode(db, user.id, r.challengeId, code, sms!.id);
    await assert.rejects(() => verifyCode(db, user.id, r.challengeId, code, sms!.id), /expired/i, "single use");

    // attempt limit on a fresh challenge
    await db.update(schema.mfaChallenges).set({ createdAt: new Date(Date.now() - 120000) }).where(eq(schema.mfaChallenges.userId, user.id));
    const [email] = await db.insert(schema.mfaMethods).values({ userId: user.id, type: "email", target: user.email, verifiedAt: new Date() }).returning();
    const r2 = await sendCode(db, user, email!, "login");
    for (let i = 0; i < 5; i++) await assert.rejects(() => verifyCode(db, user.id, r2.challengeId, "000001", email!.id));
    const real = logged.join("\n").match(/\b(\d{6}) is your/g)!.pop()!.slice(0, 6);
    await assert.rejects(() => verifyCode(db, user.id, r2.challengeId, real, email!.id), /too many/i, "locked after 5 wrong codes");
  } finally {
    console.info = orig;
    await db.delete(schema.mfaMethods).where(eq(schema.mfaMethods.userId, user.id));
    await db.delete(schema.mfaChallenges).where(eq(schema.mfaChallenges.userId, user.id));
  }
});

test("ADM-002: backup codes — 10 issued, hashed, each works once, regenerating invalidates old ones", async () => {
  const { regenerateBackupCodes, useBackupCode, backupCodesLeft } = await import("../src/lib/security/mfa");
  const codes = await regenerateBackupCodes(db, user.id);
  assert.equal(codes.length, 10);
  const rows = await db.select().from(schema.mfaBackupCodes).where(eq(schema.mfaBackupCodes.userId, user.id));
  assert.ok(rows.every((r) => !codes.includes(r.codeHash)), "stored hashed");
  assert.equal(await useBackupCode(db, user.id, codes[0]!.toLowerCase()), true, "case-insensitive");
  assert.equal(await useBackupCode(db, user.id, codes[0]!), false, "single use");
  assert.equal(await backupCodesLeft(db, user.id), 9);
  await regenerateBackupCodes(db, user.id);
  assert.equal(await useBackupCode(db, user.id, codes[1]!), false, "old codes invalidated");
  await db.delete(schema.mfaBackupCodes).where(eq(schema.mfaBackupCodes.userId, user.id));
});

test("Account lockout after repeated wrong passwords; trusted devices verify by hashed token", async () => {
  const { recordFailedLogin, LOCK_AFTER, issueTrustedDevice, checkTrustedDevice } = await import("../src/lib/security/mfa");
  const [u] = await db.insert(schema.users).values({ email: `lock${Date.now()}@example.com`, name: "Lock Test" }).returning();
  let locked = false;
  for (let i = 0; i < LOCK_AFTER; i++) { const cur = (await db.query.users.findFirst({ where: eq(schema.users.id, u!.id) }))!; locked = await recordFailedLogin(db, cur); }
  assert.equal(locked, true);
  assert.ok((await db.query.users.findFirst({ where: eq(schema.users.id, u!.id) }))!.lockedUntil! > new Date());
  const token = await issueTrustedDevice(db, u!.id, 30, "UA", "1.2.3.4");
  assert.equal(await checkTrustedDevice(db, u!.id, token), true);
  assert.equal(await checkTrustedDevice(db, u!.id, token + "x"), false);
  const row = (await db.query.trustedDevices.findFirst({ where: eq(schema.trustedDevices.userId, u!.id) }))!;
  assert.notEqual(row.tokenHash, token, "token stored hashed");
});

test("IP allowlists (exact and CIDR) and cross-site origin checks", async () => {
  const { ipAllowed, validIpEntry, sameOrigin } = await import("../src/lib/security/request");
  assert.equal(ipAllowed("10.0.0.5", []), true, "empty = allow all");
  assert.equal(ipAllowed("103.4.145.77", ["103.4.145.0/24"]), true);
  assert.equal(ipAllowed("103.4.146.1", ["103.4.145.0/24"]), false);
  assert.equal(ipAllowed("::ffff:103.4.145.9", ["103.4.145.9"]), true);
  assert.equal(ipAllowed(null, ["1.2.3.4"]), false);
  assert.equal(validIpEntry("300.1.1.1"), false);
  const h = (o: Record<string, string>) => new Headers(o);
  assert.equal(sameOrigin(h({ host: "app.example.com", origin: "https://app.example.com" })), true);
  assert.equal(sameOrigin(h({ host: "app.example.com", origin: "https://evil.example.net" })), false);
  assert.equal(sameOrigin(h({ host: "app.example.com" })), true, "non-browser requests have no Origin");
  assert.equal(sameOrigin(h({ host: "app.example.com", origin: "null" })), false);
});

test("Password policy: length, complexity and workspace minimum", async () => {
  const { passwordProblem, checkPassword } = await import("../src/lib/auth");
  assert.ok(passwordProblem("short1"));
  assert.ok(passwordProblem("onlyletterslong"));
  assert.equal(passwordProblem("letters12345"), null);
  assert.ok(passwordProblem("letters12345", 16), "workspace minimum applies");
  assert.equal(await checkPassword("Tempest-Long-2026x"), null);
});

test("SIGNUP: email + phone OTP must both verify before the account can be created; wrong codes are counted", async () => {
  const { startRegistration, verifyRegistration, consumeRegistration } = await import("../src/lib/security/registration");
  const { codeHash } = await import("../src/lib/security/mfa");
  const email = `signup-${Date.now()}@example.com`;
  const r = await startRegistration(db, { name: "Test Owner", email, phone: "01711" + String(Date.now()).slice(-6), password: "Correct-Horse-Battery-9", country: "880" }, "127.0.0.1");
  assert.ok(r.registrationId && r.verify.email && r.verify.phone);
  assert.ok(!r.sentTo.email.includes(email.split("@")[0]!), "email is masked");
  const reg = (await db.query.registrations.findFirst({ where: eq(schema.registrations.id, r.registrationId) }))!;
  assert.ok(reg.passwordHash && !reg.passwordHash.includes("Correct-Horse"), "password is hashed");
  // plant known codes (real ones were delivered out-of-band)
  await db.update(schema.registrations).set({ emailCodeHash: codeHash(`reg:${reg.id}:email`, "123456"), phoneCodeHash: codeHash(`reg:${reg.id}:phone`, "654321") }).where(eq(schema.registrations.id, reg.id));
  await assert.rejects(verifyRegistration(db, reg.id, "email", "000000"), /not valid/);
  await assert.rejects(consumeRegistration(db, reg.id), /Verify your email/);
  await verifyRegistration(db, reg.id, "email", "123456");
  await assert.rejects(consumeRegistration(db, reg.id), /Verify your mobile/);
  await verifyRegistration(db, reg.id, "phone", "654321");
  const done = await consumeRegistration(db, reg.id);
  assert.equal(done.email, email);
  await assert.rejects(consumeRegistration(db, reg.id), /expired/, "a registration can only be used once");
  await assert.rejects(startRegistration(db, { name: "Dup", email: "admin@brandtempest.com", phone: "01711000001", password: "Correct-Horse-Battery-9" }, null), /already exists/);
  await assert.rejects(startRegistration(db, { name: "Weak", email: `weak-${Date.now()}@example.com`, phone: "01711000002", password: "password" }, null));
});

test("RESET: forgot password doesn't reveal unknown accounts; reset revokes sessions and locks out after wrong codes", async () => {
  const { startPasswordReset, completePasswordReset } = await import("../src/lib/security/registration");
  const { codeHash } = await import("../src/lib/security/mfa");
  const ghost = await startPasswordReset(db, "nobody-here@example.com");
  assert.ok(ghost.resetId, "unknown accounts get the same response shape");
  await assert.rejects(completePasswordReset(db, ghost.resetId, "123456", "Another-Strong-Pass-7"), /not valid/);
  const [target] = await db.insert(schema.users).values({ email: `reset-${Date.now()}@example.com`, name: "Reset Me", status: "active" }).returning();
  const r = await startPasswordReset(db, target!.email);
  await db.update(schema.mfaChallenges).set({ codeHash: codeHash(r.resetId, "112233") }).where(eq(schema.mfaChallenges.id, r.resetId));
  await assert.rejects(completePasswordReset(db, r.resetId, "999999", "Another-Strong-Pass-7"), /not valid/);
  await completePasswordReset(db, r.resetId, "112233", "Another-Strong-Pass-7");
  const u = (await db.query.users.findFirst({ where: eq(schema.users.id, target!.id) }))!;
  assert.ok(u.passwordHash && u.passwordChangedAt);
  await assert.rejects(completePasswordReset(db, r.resetId, "112233", "Yet-Another-Pass-8"), /not valid/, "codes are single-use");
});

test("ASSISTANT: without an AI key it answers from the product guide and only links to in-app pages", async () => {
  const saved = process.env.ANTHROPIC_API_KEY;
  delete process.env.ANTHROPIC_API_KEY;
  const { runAssistant } = await import("../src/lib/ai/assistant");
  const ws = (await db.query.workspaces.findFirst())!;
  const r = await runAssistant({ db, workspace: ws } as never, [{ role: "user", content: "open pipeline please" }]);
  assert.equal(r.source, "guide");
  assert.ok(r.actions.some((a) => a.type === "navigate" && a.href === "/pipeline"));
  const h = await runAssistant({ db, workspace: ws } as never, [{ role: "user", content: "how do I import contacts?" }]);
  assert.match(h.reply, /Import/);
  if (saved) process.env.ANTHROPIC_API_KEY = saved;
});
