import type { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { OtpPurpose } from '@prisma/client';
import { env } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { checkTotp, issueOtp, resendOtp, verifyOtp } from '../auth/two-factor.service';

/**
 * A fresh code before a risky CRM action — deleting a contact, a bulk delete,
 * an export. A borrowed session alone cannot empty or copy out the CRM.
 *
 * The code goes to the member's own email (whether or not their sign-in uses
 * one). A correct code buys a short-lived step-up token, sent back on risky
 * requests as `X-CRM-Step-Up`; it is bound to the member and lasts ten
 * minutes, so deleting several records in a row asks once.
 */

const STEP_UP_MINUTES = 10;
const TOKEN_TYPE = 'crm-step-up';
// Its own key: a step-up token must never verify as an access token.
const secret = () => `${env.JWT_ACCESS_SECRET}:${TOKEN_TYPE}`;

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

export function resendStepUp(userId: string, challengeId: string) {
  return resendOtp(challengeId, OtpPurpose.STEP_UP, userId);
}

export async function verifyStepUp(userId: string, challengeId: string, code: string) {
  await verifyOtp(challengeId, code, OtpPurpose.STEP_UP, userId);
  const stepUpToken = jwt.sign({ sub: userId, typ: TOKEN_TYPE }, secret(), { expiresIn: `${STEP_UP_MINUTES}m` });
  return { stepUpToken, expiresInSeconds: STEP_UP_MINUTES * 60 };
}

/** Step up with the authenticator app instead of an emailed code (no email sent). */
export async function verifyStepUpTotp(userId: string, code: string) {
  if ((await checkTotp(userId, code)) !== 'totp') throw new BadRequestError('That code is not right. Use the current code from your authenticator app.', 'TOTP_INVALID');
  const stepUpToken = jwt.sign({ sub: userId, typ: TOKEN_TYPE }, secret(), { expiresIn: `${STEP_UP_MINUTES}m` });
  return { stepUpToken, expiresInSeconds: STEP_UP_MINUTES * 60 };
}

function hasValidStepUp(req: Request): boolean {
  const token = req.header('x-crm-step-up');
  if (!token || !req.user) return false;
  try {
    const p = jwt.verify(token, secret()) as { sub?: string; typ?: string };
    return p.typ === TOKEN_TYPE && p.sub === req.user.sub;
  } catch {
    return false;
  }
}

/** Guard for a risky route. 403 STEP_UP_REQUIRED tells the client to ask for a code. */
export function requireStepUp(req: Request, _res: Response, next: NextFunction): void {
  if (!hasValidStepUp(req)) {
    return next(new ForbiddenError('Confirm with the code we email you to do this.', 'STEP_UP_REQUIRED'));
  }
  next();
}

/** For routes where only some actions are risky (bulk): check inside the handler. */
export function assertStepUp(req: Request) {
  if (!hasValidStepUp(req)) throw new ForbiddenError('Confirm with the code we email you to do this.', 'STEP_UP_REQUIRED');
}
