import { createHmac, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
import { OtpPurpose } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { env } from '../../config/env';
import { emailFailed, isEmailConfigured, sendEmail } from '../../lib/email';
import { otpEmail } from '../../lib/email-templates';
import { alwaysTwoStep } from '../../lib/permissions';
import { hashRecovery, matchStep, newRecoveryCodes, newTotpSecret, openSecret, otpauthUrl, sealSecret } from '../../lib/totp';
import {
  BadRequestError,
  ConflictError,
  ForbiddenError,
  NotFoundError,
  ServiceUnavailableError,
  TooManyRequestsError,
} from '../../lib/errors';

/**
 * Two-step sign-in by emailed one-time code.
 *
 * Opt-in per user, from their own profile. Turning it on proves the address
 * receives mail (ENABLE_2FA code); after that every password sign-in is
 * followed by a LOGIN code; turning it off needs a DISABLE_2FA code, so a
 * borrowed session alone cannot quietly remove it.
 *
 * Codes are six digits, live OTP_TTL_MINUTES, are stored only as an HMAC keyed
 * with a server secret and the row id, are single-use, and lock after five
 * wrong tries. The row id is the challenge id the client sends back — a
 * random UUID that is only ever handed out after the password was checked.
 *
 * Tables here are platform-level (prismaUnscoped): a LOGIN challenge exists
 * before there is a tenant context, and a Super Admin has no tenant.
 */

const CODE_LENGTH = 6;
const MAX_ATTEMPTS = 5;
const MAX_SENDS_PER_CHALLENGE = 5;
const RESEND_COOLDOWN_MS = 30_000;
const MAX_CODES_PER_HOUR = 10;

export interface OtpChallenge {
  challengeId: string;
  /** "ni•••@gmail.com" — enough to know which inbox to open, no more. */
  emailHint: string;
  expiresInSeconds: number;
  resendAfterSeconds: number;
  /** Only when AUTH_OTP_ECHO is on (never in production): the code itself. */
  devCode?: string;
}


export function maskEmail(email: string): string {
  const [local, domain] = email.split('@');
  if (!domain) return '•••';
  const keep = local.length <= 2 ? local.slice(0, 1) : local.slice(0, 2);
  return `${keep}${'•'.repeat(3)}@${domain}`;
}

function newCode(): string {
  return String(randomInt(0, 10 ** CODE_LENGTH)).padStart(CODE_LENGTH, '0');
}

/** Keyed with a server secret and bound to the row, so a leaked table is useless. */
function hashCode(otpId: string, code: string): string {
  return createHmac('sha256', `${env.JWT_REFRESH_SECRET}:email-otp`).update(`${otpId}:${code}`).digest('hex');
}

function sameHash(a: string, b: string): boolean {
  const x = Buffer.from(a, 'hex');
  const y = Buffer.from(b, 'hex');
  return x.length === y.length && timingSafeEqual(x, y);
}

async function deliver(to: string, name: string, purpose: OtpPurpose, code: string) {
  const mail = otpEmail({ name, code, minutes: env.OTP_TTL_MINUTES, purpose });
  return sendEmail(to, mail.subject, mail.text, mail.html);
}

/**
 * Turning 2FA on in an environment that cannot send mail would lock people
 * out at their next sign-in. Development runs in dry-run mode and logs the
 * code instead; anywhere else, refuse until email is configured.
 */
function assertCanDeliver() {
  if (isEmailConfigured()) return;
  if (env.NODE_ENV === 'development' || env.NODE_ENV === 'test') return;
  throw new ServiceUnavailableError(
    'Email delivery is not configured on this server, so verification codes cannot be sent.',
    'EMAIL_NOT_CONFIGURED',
  );
}

async function sendOrFail(otpId: string, user: { email: string; name: string }, purpose: OtpPurpose, code: string) {
  const result = await deliver(user.email, user.name, purpose, code);
  if (emailFailed(result)) {
    throw new ServiceUnavailableError('We could not send the verification email. Try again in a moment.', 'EMAIL_SEND_FAILED');
  }
  if (result.mode === 'log') {
    // Dry-run only (development/test): the code has nowhere else to go.
    // eslint-disable-next-line no-console
    console.log(`[2fa dry-run] ${purpose} code for ${user.email}: ${code} (challenge ${otpId})`);
  }
}

function challengeOf(otpId: string, email: string, code: string, lastSentAt: Date, expiresAt: Date): OtpChallenge {
  return {
    challengeId: otpId,
    emailHint: maskEmail(email),
    expiresInSeconds: Math.max(0, Math.round((expiresAt.getTime() - Date.now()) / 1000)),
    resendAfterSeconds: Math.max(0, Math.round((lastSentAt.getTime() + RESEND_COOLDOWN_MS - Date.now()) / 1000)),
    ...(env.AUTH_OTP_ECHO ? { devCode: code } : {}),
  };
}

/** Send a fresh code for `purpose`, retiring any earlier one for the same purpose. */
export async function issueOtp(user: { id: string; email: string; name: string }, purpose: OtpPurpose): Promise<OtpChallenge> {
  assertCanDeliver();

  const hourAgo = new Date(Date.now() - 60 * 60 * 1000);
  const recent = await prismaUnscoped.emailOtp.aggregate({
    where: { userId: user.id, createdAt: { gte: hourAgo } },
    _sum: { sends: true },
  });
  if ((recent._sum.sends ?? 0) >= MAX_CODES_PER_HOUR) {
    throw new TooManyRequestsError('Too many verification codes requested. Wait a while and try again.', 'OTP_RATE_LIMITED');
  }

  // Housekeeping: codes are worthless a day on. Bounded by the index.
  await prismaUnscoped.emailOtp.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 24 * 60 * 60 * 1000) } } });
  // Only the newest code for a purpose is ever valid.
  await prismaUnscoped.emailOtp.updateMany({
    where: { userId: user.id, purpose, consumedAt: null },
    data: { consumedAt: new Date() },
  });

  const id = randomUUID();
  const code = newCode();
  const now = new Date();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  await prismaUnscoped.emailOtp.create({
    data: { id, userId: user.id, purpose, codeHash: hashCode(id, code), expiresAt, lastSentAt: now },
  });

  try {
    await sendOrFail(id, user, purpose, code);
  } catch (e) {
    // A code nobody received must not count against them or linger.
    await prismaUnscoped.emailOtp.delete({ where: { id } }).catch(() => {});
    throw e;
  }
  return challengeOf(id, user.email, code, now, expiresAt);
}

/**
 * Send a new code on an existing challenge. The old code stops working and
 * the clock restarts, but the attempt counter carries over — resending is
 * not a way to earn more guesses.
 */
export async function resendOtp(challengeId: string, purpose: OtpPurpose, ownerUserId?: string): Promise<OtpChallenge> {
  assertCanDeliver();
  const otp = await prismaUnscoped.emailOtp.findFirst({
    where: { id: challengeId, purpose, consumedAt: null, ...(ownerUserId ? { userId: ownerUserId } : {}) },
    include: { user: { select: { id: true, email: true, name: true } } },
  });
  if (!otp) throw new NotFoundError('This verification has ended. Start again.', 'OTP_CHALLENGE_NOT_FOUND');
  if (otp.attempts >= MAX_ATTEMPTS) {
    throw new TooManyRequestsError('Too many wrong codes. Start again.', 'OTP_LOCKED');
  }
  if (otp.sends >= MAX_SENDS_PER_CHALLENGE) {
    throw new TooManyRequestsError('That code has been resent too many times. Start again.', 'OTP_RESEND_LIMIT');
  }
  const wait = otp.lastSentAt.getTime() + RESEND_COOLDOWN_MS - Date.now();
  if (wait > 0) {
    throw new TooManyRequestsError(`Wait ${Math.ceil(wait / 1000)} seconds before asking for another code.`, 'OTP_RESEND_COOLDOWN');
  }

  const code = newCode();
  const now = new Date();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  await prismaUnscoped.emailOtp.update({
    where: { id: otp.id },
    data: { codeHash: hashCode(otp.id, code), expiresAt, lastSentAt: now, sends: { increment: 1 } },
  });
  await sendOrFail(otp.id, otp.user, purpose, code);
  return challengeOf(otp.id, otp.user.email, code, now, expiresAt);
}

/**
 * Check a code. Returns the user id it belongs to and consumes it on success.
 * `ownerUserId` pins the challenge to a signed-in user for the profile flows.
 */
export async function verifyOtp(challengeId: string, code: string, purpose: OtpPurpose, ownerUserId?: string): Promise<string> {
  const otp = await prismaUnscoped.emailOtp.findFirst({
    where: { id: challengeId, purpose, ...(ownerUserId ? { userId: ownerUserId } : {}) },
  });
  if (!otp || otp.consumedAt) {
    throw new BadRequestError('This code is no longer valid. Request a new one.', 'OTP_EXPIRED');
  }
  if (otp.attempts >= MAX_ATTEMPTS) {
    throw new TooManyRequestsError('Too many wrong codes. Start again.', 'OTP_LOCKED');
  }
  if (otp.expiresAt.getTime() < Date.now()) {
    throw new BadRequestError('This code has expired. Request a new one.', 'OTP_EXPIRED');
  }

  if (!/^\d{6}$/.test(code) || !sameHash(otp.codeHash, hashCode(otp.id, code))) {
    const updated = await prismaUnscoped.emailOtp.update({
      where: { id: otp.id },
      data: { attempts: { increment: 1 } },
      select: { attempts: true },
    });
    const left = MAX_ATTEMPTS - updated.attempts;
    if (left <= 0) throw new TooManyRequestsError('Too many wrong codes. Start again.', 'OTP_LOCKED');
    throw new BadRequestError(`That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`, 'OTP_INVALID');
  }

  // Single use, even under a race: only one update can flip consumedAt.
  const claimed = await prismaUnscoped.emailOtp.updateMany({
    where: { id: otp.id, consumedAt: null },
    data: { consumedAt: new Date() },
  });
  if (claimed.count !== 1) throw new BadRequestError('This code is no longer valid. Request a new one.', 'OTP_EXPIRED');
  return otp.userId;
}

// ── Profile flows (signed-in user) ─────────────────────────────────────────

async function loadSelf(userId: string) {
  const user = await prismaUnscoped.user.findUnique({
    where: { id: userId },
    select: { id: true, email: true, name: true, twoFactorEnabled: true, role: true },
  });
  if (!user) throw new NotFoundError('User not found');
  return user;
}

export async function startEnable(userId: string): Promise<OtpChallenge> {
  const user = await loadSelf(userId);
  if (user.twoFactorEnabled) throw new ConflictError('Two-step verification is already on.', 'TWO_FACTOR_ALREADY_ON');
  return issueOtp(user, OtpPurpose.ENABLE_2FA);
}

export async function confirmEnable(userId: string, challengeId: string, code: string) {
  await verifyOtp(challengeId, code, OtpPurpose.ENABLE_2FA, userId);
  await prismaUnscoped.user.update({
    where: { id: userId },
    data: { twoFactorEnabled: true, twoFactorEnabledAt: new Date() },
  });
}

export async function startDisable(userId: string): Promise<OtpChallenge> {
  const user = await loadSelf(userId);
  if (alwaysTwoStep(user.role)) {
    throw new ForbiddenError('Two-step verification is required for this account.', 'TWO_FACTOR_REQUIRED');
  }
  if (!user.twoFactorEnabled) throw new ConflictError('Two-step verification is already off.', 'TWO_FACTOR_ALREADY_OFF');
  return issueOtp(user, OtpPurpose.DISABLE_2FA);
}

export async function confirmDisable(userId: string, challengeId: string, code: string) {
  await verifyOtp(challengeId, code, OtpPurpose.DISABLE_2FA, userId);
  await prismaUnscoped.user.update({
    where: { id: userId },
    data: { twoFactorEnabled: false, twoFactorEnabledAt: null },
  });
  // Any half-finished sign-in challenge is moot now.
  await prismaUnscoped.emailOtp.updateMany({
    where: { userId, purpose: OtpPurpose.LOGIN, consumedAt: null },
    data: { consumedAt: new Date() },
  });
}

/** Which profile purpose a resend is for — the client says, the row must agree. */
export function profilePurpose(value: 'enable' | 'disable'): OtpPurpose {
  return value === 'enable' ? OtpPurpose.ENABLE_2FA : OtpPurpose.DISABLE_2FA;
}

// ── Authenticator app (TOTP, 10 Oct 2026) ──────────────────────────────────
//
// A second way to pass the second step, alongside the emailed code. Set up
// from the profile: a secret shown as a QR code, confirmed with its first
// code, plus eight one-time recovery codes. At sign-in a client that says
// supportsTotp is asked for the app's code first — no email is sent unless
// the person asks for one. Older clients keep getting the emailed code.

async function loadTotp(userId: string) {
  const user = await prismaUnscoped.user.findUnique({
    where: { id: userId },
    select: { id: true, email: true, name: true, totpSecret: true, totpPendingSecret: true, totpEnabledAt: true, totpLastStep: true, totpRecoveryHashes: true },
  });
  if (!user) throw new NotFoundError('User not found');
  return user;
}

/** Start (or restart) setting up an authenticator app: a fresh secret, not yet live. */
export async function totpSetup(userId: string) {
  const user = await loadTotp(userId);
  if (user.totpEnabledAt) throw new ConflictError('An authenticator app is already set up. Turn it off first to switch phones.', 'TOTP_ALREADY_ON');
  const secret = newTotpSecret();
  await prismaUnscoped.user.update({ where: { id: userId }, data: { totpPendingSecret: sealSecret(secret) } });
  return { secret, otpauthUrl: otpauthUrl(secret, user.email) };
}

/** Confirm the app with its first code; returns the recovery codes, shown once. */
export async function totpEnable(userId: string, code: string) {
  const user = await loadTotp(userId);
  if (user.totpEnabledAt) throw new ConflictError('An authenticator app is already set up.', 'TOTP_ALREADY_ON');
  if (!user.totpPendingSecret) throw new BadRequestError('Start the set-up again to get a new QR code.', 'TOTP_NO_SETUP');
  const step = matchStep(openSecret(user.totpPendingSecret), code.trim(), null);
  if (step === null) throw new BadRequestError('That code is not right. Check the time on your phone and try the current code.', 'TOTP_INVALID');
  const codes = newRecoveryCodes();
  await prismaUnscoped.user.update({
    where: { id: userId },
    data: { totpSecret: user.totpPendingSecret, totpPendingSecret: null, totpEnabledAt: new Date(), totpLastStep: step, totpRecoveryHashes: codes.map(hashRecovery) },
  });
  return { recoveryCodes: codes };
}

/**
 * Check an authenticator code — or a recovery code — for a user who has the
 * app set up. A code is good once (its step is remembered); a recovery code
 * is removed when used. Returns how it was passed.
 */
export async function checkTotp(userId: string, raw: string): Promise<'totp' | 'recovery' | null> {
  const user = await loadTotp(userId);
  if (!user.totpEnabledAt || !user.totpSecret) return null;
  const code = raw.trim();
  if (/^\d{6}$/.test(code.replace(/\s/g, ''))) {
    const step = matchStep(openSecret(user.totpSecret), code.replace(/\s/g, ''), user.totpLastStep ?? null);
    if (step === null) return null;
    // Only one sign-in per step, even under a race.
    const r = await prismaUnscoped.user.updateMany({ where: { id: userId, OR: [{ totpLastStep: null }, { totpLastStep: { lt: step } }] }, data: { totpLastStep: step } });
    return r.count === 1 ? 'totp' : null;
  }
  const h = hashRecovery(code);
  if (!user.totpRecoveryHashes.includes(h)) return null;
  await prismaUnscoped.user.update({ where: { id: userId }, data: { totpRecoveryHashes: user.totpRecoveryHashes.filter((x) => x !== h) } });
  return 'recovery';
}

/** Turn the app off — proven with a current code or a recovery code. */
export async function totpDisable(userId: string, code: string) {
  const user = await loadTotp(userId);
  if (!user.totpEnabledAt) throw new ConflictError('No authenticator app is set up.', 'TOTP_ALREADY_OFF');
  if (!(await checkTotp(userId, code))) throw new BadRequestError('That code is not right.', 'TOTP_INVALID');
  await prismaUnscoped.user.update({ where: { id: userId }, data: { totpSecret: null, totpPendingSecret: null, totpEnabledAt: null, totpLastStep: null, totpRecoveryHashes: [] } });
}

/** A fresh set of recovery codes (the old ones stop working), proven with a current code. */
export async function totpNewRecoveryCodes(userId: string, code: string) {
  const user = await loadTotp(userId);
  if (!user.totpEnabledAt) throw new ConflictError('No authenticator app is set up.', 'TOTP_ALREADY_OFF');
  if ((await checkTotp(userId, code)) !== 'totp') throw new BadRequestError('Enter the current code from your authenticator app.', 'TOTP_INVALID');
  const codes = newRecoveryCodes();
  await prismaUnscoped.user.update({ where: { id: userId }, data: { totpRecoveryHashes: codes.map(hashRecovery) } });
  return { recoveryCodes: codes };
}

export const recoveryCodesLeft = async (userId: string) => (await loadTotp(userId)).totpRecoveryHashes.length;

// ── Sign-in with a choice of method ────────────────────────────────────────

export type LoginChallenge = OtpChallenge & { methods: ('totp' | 'email')[]; method: 'totp' | 'email' };

/**
 * A sign-in challenge with nothing sent yet: the person will answer with
 * their authenticator app, or ask for an emailed code (emailLoginCode).
 * Uses the same row as an emailed code, so attempts and expiry behave alike.
 */
export async function openLoginChallenge(user: { id: string; email: string }): Promise<LoginChallenge> {
  await prismaUnscoped.emailOtp.updateMany({ where: { userId: user.id, purpose: OtpPurpose.LOGIN, consumedAt: null }, data: { consumedAt: new Date() } });
  const id = randomUUID();
  const now = new Date();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  // An unguessable placeholder until a code is emailed.
  await prismaUnscoped.emailOtp.create({ data: { id, userId: user.id, purpose: OtpPurpose.LOGIN, codeHash: hashCode(id, randomUUID()), sends: 0, expiresAt, lastSentAt: new Date(0) } });
  return { challengeId: id, emailHint: maskEmail(user.email), expiresInSeconds: env.OTP_TTL_MINUTES * 60, resendAfterSeconds: 0, methods: ['totp', 'email'], method: 'totp' };
}

/** "Email me a code instead": the first email on a challenge goes at once; later ones are resends. */
export async function emailLoginCode(challengeId: string): Promise<OtpChallenge> {
  const otp = await prismaUnscoped.emailOtp.findFirst({ where: { id: challengeId, purpose: OtpPurpose.LOGIN, consumedAt: null }, include: { user: { select: { id: true, email: true, name: true } } } });
  if (!otp) throw new NotFoundError('This verification has ended. Start again.', 'OTP_CHALLENGE_NOT_FOUND');
  if (otp.sends > 0) return resendOtp(challengeId, OtpPurpose.LOGIN);
  assertCanDeliver();
  const hourAgo = new Date(Date.now() - 60 * 60 * 1000);
  const recent = await prismaUnscoped.emailOtp.aggregate({ where: { userId: otp.userId, createdAt: { gte: hourAgo } }, _sum: { sends: true } });
  if ((recent._sum.sends ?? 0) >= MAX_CODES_PER_HOUR) throw new TooManyRequestsError('Too many verification codes requested. Wait a while and try again.', 'OTP_RATE_LIMITED');
  const code = newCode();
  const now = new Date();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  await prismaUnscoped.emailOtp.update({ where: { id: otp.id }, data: { codeHash: hashCode(otp.id, code), sends: 1, lastSentAt: now, expiresAt } });
  await sendOrFail(otp.id, otp.user, OtpPurpose.LOGIN, code);
  return challengeOf(otp.id, otp.user.email, code, now, expiresAt);
}

/** Answer a sign-in challenge with the authenticator app (or a recovery code). */
export async function verifyLoginTotp(challengeId: string, code: string): Promise<{ userId: string; via: 'totp' | 'recovery' }> {
  const otp = await prismaUnscoped.emailOtp.findFirst({ where: { id: challengeId, purpose: OtpPurpose.LOGIN } });
  if (!otp || otp.consumedAt) throw new BadRequestError('This sign-in has ended. Start again.', 'OTP_EXPIRED');
  if (otp.attempts >= MAX_ATTEMPTS) throw new TooManyRequestsError('Too many wrong codes. Start again.', 'OTP_LOCKED');
  if (otp.expiresAt.getTime() < Date.now()) throw new BadRequestError('This sign-in has expired. Start again.', 'OTP_EXPIRED');
  const via = await checkTotp(otp.userId, code);
  if (!via) {
    const u = await prismaUnscoped.emailOtp.update({ where: { id: otp.id }, data: { attempts: { increment: 1 } }, select: { attempts: true } });
    const left = MAX_ATTEMPTS - u.attempts;
    if (left <= 0) throw new TooManyRequestsError('Too many wrong codes. Start again.', 'OTP_LOCKED');
    throw new BadRequestError(`That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`, 'TOTP_INVALID');
  }
  const claimed = await prismaUnscoped.emailOtp.updateMany({ where: { id: otp.id, consumedAt: null }, data: { consumedAt: new Date() } });
  if (claimed.count !== 1) throw new BadRequestError('This sign-in has ended. Start again.', 'OTP_EXPIRED');
  return { userId: otp.userId, via };
}
