/**
 * Two-factor authentication (ADM-002 / NFR-003): authenticator apps (TOTP), email codes, SMS codes,
 * passkeys & security keys (WebAuthn), one-time backup codes and "remember this device".
 * - TOTP secrets are AES-256-GCM encrypted and each 30-second step can be used once (replay protection)
 * - email/SMS codes: 6 digits, 10 minutes, 5 attempts, stored as keyed hashes, resend cool-down and hourly cap
 * - backup codes: 10 single-use codes, keyed hashes, shown once
 */
import crypto from "node:crypto";
import { and, desc, eq, gt, gte, isNull, sql } from "drizzle-orm";
import { schema, type DB } from "@/db";
import { ApiError } from "@/lib/api";
import { base32Encode, decrypt, encrypt, safeEqual, totp } from "@/lib/crypto";
import type { SecuritySettings } from "@/db/schema";
import { sendSecurityEmail, sendSecuritySms } from "./deliver";

export type MfaType = "totp" | "email" | "sms" | "webauthn";
export const MFA_TYPES: MfaType[] = ["webauthn", "totp", "sms", "email"];
export const MFA_LABEL: Record<MfaType | "backup", string> = { totp: "Authenticator app", email: "Email code", sms: "SMS code", webauthn: "Passkey / security key", backup: "Backup code" };
type Method = typeof schema.mfaMethods.$inferSelect;
type User = typeof schema.users.$inferSelect;

const pepper = () => process.env.AUTH_SECRET ?? "tempest-pulse-dev-secret-change-me";
/** Keyed hash so short codes can't be brute-forced offline from a database copy. */
export const codeHash = (scope: string, code: string) => crypto.createHmac("sha256", pepper()).update(`${scope}:${code.replace(/[\s-]/g, "").toUpperCase()}`).digest("hex");
const sixDigits = () => String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");

export const maskEmail = (e: string) => e.replace(/^(.)(.*)(@.*)$/, (_m, a: string, b: string, c: string) => `${a}${"•".repeat(Math.min(Math.max(b.length, 2), 6))}${c}`);
export const maskPhone = (p: string) => `${p.slice(0, 4)}••••${p.slice(-3)}`;
export const maskTarget = (m: Pick<Method, "type" | "target">) => (m.type === "email" && m.target ? maskEmail(m.target) : m.type === "sms" && m.target ? maskPhone(m.target) : null);

export const publicMethod = (m: Method) => ({ id: m.id, type: m.type as MfaType, label: m.label ?? MFA_LABEL[m.type as MfaType], target: maskTarget(m), verified: !!m.verifiedAt, lastUsedAt: m.lastUsedAt, createdAt: m.createdAt });

/** Verified methods; migrates a legacy plaintext `users.mfa_secret` into an encrypted TOTP method on first use. */
export async function userMethods(db: DB, user: Pick<User, "id" | "mfaSecret" | "mfaEnabled">, includeUnverified = false) {
  if (user.mfaSecret) {
    if (user.mfaEnabled) await db.insert(schema.mfaMethods).values({ userId: user.id, type: "totp", label: "Authenticator app", secretEnc: encrypt(user.mfaSecret), verifiedAt: new Date() });
    await db.update(schema.users).set({ mfaSecret: null }).where(eq(schema.users.id, user.id));
  }
  const rows = await db.select().from(schema.mfaMethods).where(eq(schema.mfaMethods.userId, user.id)).orderBy(desc(schema.mfaMethods.createdAt));
  return includeUnverified ? rows : rows.filter((m) => m.verifiedAt);
}

/** Keep users.mfa_enabled in sync with "has at least one verified method". */
export async function refreshMfaFlag(db: DB, userId: string) {
  const [{ n }] = (await db.select({ n: sql<number>`count(*)::int` }).from(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, userId), sql`${schema.mfaMethods.verifiedAt} IS NOT NULL`))) as [{ n: number }];
  await db.update(schema.users).set({ mfaEnabled: n > 0 }).where(eq(schema.users.id, userId));
  return n > 0;
}

export function allowedTypes(security?: SecuritySettings | null): MfaType[] {
  const a = security?.allowedMfaMethods?.filter((t) => MFA_TYPES.includes(t));
  return a?.length ? a : MFA_TYPES;
}

/* ---------------- authenticator app (TOTP) ---------------- */

export async function startTotp(db: DB, userId: string, label?: string) {
  await db.delete(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, userId), eq(schema.mfaMethods.type, "totp"), isNull(schema.mfaMethods.verifiedAt)));
  const secret = base32Encode(crypto.randomBytes(20));
  const [m] = await db.insert(schema.mfaMethods).values({ userId, type: "totp", label: label?.slice(0, 60) || "Authenticator app", secretEnc: encrypt(secret) }).returning();
  return { method: m!, secret };
}

/** Returns true and records the step when the code is valid and not already used. */
export async function checkTotp(db: DB, m: Method, code: string) {
  if (!m.secretEnc) return false;
  const secret = decrypt(m.secretEnc);
  const c = code.replace(/\s/g, "");
  const now = Math.floor(Date.now() / 30000);
  for (const w of [0, -1, 1]) {
    const step = now + w;
    if (m.lastUsedStep != null && step <= m.lastUsedStep) continue; // replay / older code
    if (safeEqual(totp(secret, step * 30000), c)) {
      await db.update(schema.mfaMethods).set({ lastUsedStep: step, lastUsedAt: new Date() }).where(eq(schema.mfaMethods.id, m.id));
      return true;
    }
  }
  return false;
}

/* ---------------- email & SMS codes ---------------- */

async function throttle(db: DB, userId: string) {
  const recent = await db.select({ at: schema.mfaChallenges.createdAt }).from(schema.mfaChallenges).where(and(eq(schema.mfaChallenges.userId, userId), eq(schema.mfaChallenges.kind, "code"), gte(schema.mfaChallenges.createdAt, new Date(Date.now() - 3600000)))).orderBy(desc(schema.mfaChallenges.createdAt));
  if (recent[0] && Date.now() - recent[0].at.getTime() < 45000) throw new ApiError(429, "too_soon", "Please wait a few seconds before requesting another code");
  if (recent.length >= 8) throw new ApiError(429, "too_many_codes", "Too many codes requested — try again in an hour or use another method");
}

/** Sends a code to an email/SMS method (login or enrolment) and returns the challenge id. */
export async function sendCode(db: DB, user: Pick<User, "id" | "name">, m: Method, purpose: "login" | "enroll" | "step_up", sessionId?: string | null) {
  if ((m.type !== "email" && m.type !== "sms") || !m.target) throw new ApiError(422, "validation_failed", "This method does not use codes");
  await throttle(db, user.id);
  const code = sixDigits();
  const [c] = await db.insert(schema.mfaChallenges).values({ userId: user.id, sessionId: sessionId ?? null, methodId: m.id, purpose, kind: "code", codeHash: "pending", expiresAt: new Date(Date.now() + 10 * 60000) }).returning();
  await db.update(schema.mfaChallenges).set({ codeHash: codeHash(c!.id, code) }).where(eq(schema.mfaChallenges.id, c!.id));
  const product = process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse";
  const text = `${code} is your ${product} verification code. It expires in 10 minutes. Never share this code with anyone — our team will never ask for it.`;
  if (m.type === "email") await sendSecurityEmail(db, user.id, m.target, `${code} is your ${product} verification code`, `Hi ${user.name},\n\n${text}\n\nIf you didn't try to sign in, change your password now.`);
  else await sendSecuritySms(db, user.id, m.target, text);
  return { challengeId: c!.id, expiresAt: c!.expiresAt };
}

export async function verifyCode(db: DB, userId: string, challengeId: string, code: string, methodId?: string) {
  const c = await db.query.mfaChallenges.findFirst({ where: and(eq(schema.mfaChallenges.id, challengeId), eq(schema.mfaChallenges.userId, userId), eq(schema.mfaChallenges.kind, "code")) });
  if (!c || c.consumedAt || c.expiresAt < new Date()) throw new ApiError(400, "code_expired", "This code has expired — request a new one");
  if (methodId && c.methodId !== methodId) throw new ApiError(400, "invalid_code", "That code is not valid");
  if (c.attempts >= 5) throw new ApiError(429, "too_many_attempts", "Too many wrong codes — request a new one");
  if (!c.codeHash || !safeEqual(c.codeHash, codeHash(c.id, code))) {
    await db.update(schema.mfaChallenges).set({ attempts: c.attempts + 1 }).where(eq(schema.mfaChallenges.id, c.id));
    throw new ApiError(400, "invalid_code", "That code is not valid");
  }
  await db.update(schema.mfaChallenges).set({ consumedAt: new Date() }).where(eq(schema.mfaChallenges.id, c.id));
  if (c.methodId) await db.update(schema.mfaMethods).set({ lastUsedAt: new Date() }).where(eq(schema.mfaMethods.id, c.methodId));
  return c;
}

/* ---------------- backup codes ---------------- */

export async function regenerateBackupCodes(db: DB, userId: string) {
  await db.delete(schema.mfaBackupCodes).where(eq(schema.mfaBackupCodes.userId, userId));
  const codes = Array.from({ length: 10 }, () => { const s = base32Encode(crypto.randomBytes(5)).slice(0, 8); return `${s.slice(0, 4)}-${s.slice(4)}`; });
  await db.insert(schema.mfaBackupCodes).values(codes.map((c) => ({ userId, codeHash: codeHash(`backup:${userId}`, c) })));
  return codes;
}

export async function useBackupCode(db: DB, userId: string, code: string) {
  const h = codeHash(`backup:${userId}`, code);
  const row = await db.query.mfaBackupCodes.findFirst({ where: and(eq(schema.mfaBackupCodes.userId, userId), eq(schema.mfaBackupCodes.codeHash, h), isNull(schema.mfaBackupCodes.usedAt)) });
  if (!row) return false;
  const r = await db.update(schema.mfaBackupCodes).set({ usedAt: new Date() }).where(and(eq(schema.mfaBackupCodes.id, row.id), isNull(schema.mfaBackupCodes.usedAt))).returning();
  return r.length === 1;
}

export async function backupCodesLeft(db: DB, userId: string) {
  const [{ n }] = (await db.select({ n: sql<number>`count(*)::int` }).from(schema.mfaBackupCodes).where(and(eq(schema.mfaBackupCodes.userId, userId), isNull(schema.mfaBackupCodes.usedAt)))) as [{ n: number }];
  return n;
}

/* ---------------- passkeys / security keys (WebAuthn) ---------------- */

export function rp(req: { headers: Headers; nextUrl?: URL }) {
  const app = process.env.APP_URL ? new URL(process.env.APP_URL) : null;
  const host = (req.headers.get("x-forwarded-host") ?? req.headers.get("host") ?? app?.host ?? "localhost").split(",")[0]!.trim();
  const proto = req.headers.get("x-forwarded-proto") ?? (host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https");
  return { rpID: host.split(":")[0]!, origin: `${proto}://${host}`, rpName: process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse" };
}

export async function webauthnRegistrationOptions(db: DB, user: Pick<User, "id" | "email" | "name">, r: ReturnType<typeof rp>) {
  const { generateRegistrationOptions } = await import("@simplewebauthn/server");
  const existing = (await db.select().from(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, user.id), eq(schema.mfaMethods.type, "webauthn")))).filter((m) => m.credentialId);
  const options = await generateRegistrationOptions({
    rpName: r.rpName, rpID: r.rpID, userName: user.email, userDisplayName: user.name, userID: new TextEncoder().encode(user.id), attestationType: "none",
    excludeCredentials: existing.map((m) => ({ id: m.credentialId!, transports: m.transports as never })),
    authenticatorSelection: { residentKey: "preferred", userVerification: "preferred" },
  });
  await db.insert(schema.mfaChallenges).values({ userId: user.id, purpose: "enroll", kind: "webauthn", challenge: options.challenge, expiresAt: new Date(Date.now() + 5 * 60000) });
  return options;
}

async function latestChallenge(db: DB, userId: string, purpose: string) {
  const c = await db.query.mfaChallenges.findFirst({ where: and(eq(schema.mfaChallenges.userId, userId), eq(schema.mfaChallenges.kind, "webauthn"), eq(schema.mfaChallenges.purpose, purpose), isNull(schema.mfaChallenges.consumedAt), gt(schema.mfaChallenges.expiresAt, new Date())), orderBy: desc(schema.mfaChallenges.createdAt) });
  if (!c?.challenge) throw new ApiError(400, "challenge_expired", "The security-key request expired — try again");
  await db.update(schema.mfaChallenges).set({ consumedAt: new Date() }).where(eq(schema.mfaChallenges.id, c.id));
  return c.challenge;
}

export async function webauthnRegister(db: DB, userId: string, response: unknown, label: string | undefined, r: ReturnType<typeof rp>) {
  const { verifyRegistrationResponse } = await import("@simplewebauthn/server");
  const expectedChallenge = await latestChallenge(db, userId, "enroll");
  const v = await verifyRegistrationResponse({ response: response as never, expectedChallenge, expectedOrigin: r.origin, expectedRPID: r.rpID }).catch((e) => { throw new ApiError(400, "webauthn_failed", (e as Error).message); });
  if (!v.verified) throw new ApiError(400, "webauthn_failed", "The passkey could not be verified");
  const cred = v.registrationInfo.credential;
  const [m] = await db.insert(schema.mfaMethods).values({
    userId, type: "webauthn", label: label?.slice(0, 60) || (v.registrationInfo.credentialDeviceType === "multiDevice" ? "Passkey" : "Security key"),
    credentialId: cred.id, publicKey: Buffer.from(cred.publicKey).toString("base64url"), counter: cred.counter, transports: (cred.transports ?? []) as string[], verifiedAt: new Date(),
  }).returning();
  return m!;
}

export async function webauthnAuthOptions(db: DB, userId: string, r: ReturnType<typeof rp>) {
  const { generateAuthenticationOptions } = await import("@simplewebauthn/server");
  const creds = (await db.select().from(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, userId), eq(schema.mfaMethods.type, "webauthn")))).filter((m) => m.credentialId && m.verifiedAt);
  if (!creds.length) throw new ApiError(400, "no_passkey", "No passkey or security key is registered");
  const options = await generateAuthenticationOptions({ rpID: r.rpID, userVerification: "preferred", allowCredentials: creds.map((m) => ({ id: m.credentialId!, transports: m.transports as never })) });
  await db.insert(schema.mfaChallenges).values({ userId, purpose: "login", kind: "webauthn", challenge: options.challenge, expiresAt: new Date(Date.now() + 5 * 60000) });
  return options;
}

export async function webauthnAuthenticate(db: DB, userId: string, response: { id?: string } & Record<string, unknown>, r: ReturnType<typeof rp>) {
  const { verifyAuthenticationResponse } = await import("@simplewebauthn/server");
  const m = response.id ? await db.query.mfaMethods.findFirst({ where: and(eq(schema.mfaMethods.userId, userId), eq(schema.mfaMethods.credentialId, String(response.id))) }) : null;
  if (!m?.publicKey || !m.verifiedAt) throw new ApiError(400, "unknown_credential", "This passkey is not registered to your account");
  const expectedChallenge = await latestChallenge(db, userId, "login");
  const v = await verifyAuthenticationResponse({
    response: response as never, expectedChallenge, expectedOrigin: r.origin, expectedRPID: r.rpID,
    credential: { id: m.credentialId!, publicKey: new Uint8Array(Buffer.from(m.publicKey, "base64url")), counter: m.counter, transports: m.transports as never },
  }).catch((e) => { throw new ApiError(400, "webauthn_failed", (e as Error).message); });
  if (!v.verified) throw new ApiError(400, "webauthn_failed", "The passkey could not be verified");
  await db.update(schema.mfaMethods).set({ counter: v.authenticationInfo.newCounter, lastUsedAt: new Date() }).where(eq(schema.mfaMethods.id, m.id));
  return m;
}

/* ---------------- trusted devices ---------------- */

export const TRUSTED_COOKIE = "tp_td";
export async function issueTrustedDevice(db: DB, userId: string, days: number, ua?: string | null, ip?: string | null) {
  const token = crypto.randomBytes(32).toString("base64url");
  await db.insert(schema.trustedDevices).values({ userId, tokenHash: codeHash("td", token), userAgent: ua?.slice(0, 250) ?? null, ip: ip ?? null, expiresAt: new Date(Date.now() + days * 86400000) });
  return token;
}
export async function checkTrustedDevice(db: DB, userId: string, token: string | undefined | null) {
  if (!token) return false;
  const row = await db.query.trustedDevices.findFirst({ where: and(eq(schema.trustedDevices.userId, userId), eq(schema.trustedDevices.tokenHash, codeHash("td", token)), gt(schema.trustedDevices.expiresAt, new Date())) });
  if (!row) return false;
  await db.update(schema.trustedDevices).set({ lastUsedAt: new Date() }).where(eq(schema.trustedDevices.id, row.id));
  return true;
}

/* ---------------- account lockout ---------------- */

export const LOCK_AFTER = 8;
export const LOCK_MINUTES = 15;
export async function recordFailedLogin(db: DB, user: User) {
  const failed = user.failedLogins + 1;
  const lock = failed >= LOCK_AFTER;
  await db.update(schema.users).set({ failedLogins: lock ? 0 : failed, ...(lock ? { lockedUntil: new Date(Date.now() + LOCK_MINUTES * 60000) } : {}) }).where(eq(schema.users.id, user.id));
  return lock;
}
