import type { NextFunction, Request, Response } from 'express';
import { Role } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { ForbiddenError, UnauthorizedError } from '../../lib/errors';
import type { Actor } from './crm-users.service';

const CRM_ROLES: Role[] = [Role.SUPER_ADMIN, Role.CRM_USER];

/**
 * The CRM's door: the super admin and CRM users only, and only while the
 * account is switched on and the session predates no "sign out everywhere".
 *
 * Checked against the database on every CRM request (one indexed lookup), so
 * switching a CRM user off ends their access at once rather than when their
 * access token runs out. A 401 makes the web app try a refresh, which is then
 * refused with the reason, and it signs them out.
 */
export function requireCrmAccess(req: Request, res: Response, next: NextFunction): void {
  impl(req, res).then(() => next(), next);
}

async function impl(req: Request, res: Response) {
  if (!req.user) throw new UnauthorizedError();
  if (!CRM_ROLES.includes(req.user.role)) throw new ForbiddenError('The CRM is for the platform team.');
  const u = await prismaUnscoped.user.findUnique({
    where: { id: req.user.sub },
    select: { id: true, name: true, email: true, deactivatedAt: true, sessionsRevokedAt: true },
  });
  if (!u || u.deactivatedAt) throw new UnauthorizedError('This account has been switched off.');
  const iat = req.user.iat;
  if (u.sessionsRevokedAt && iat !== undefined && iat < Math.floor(u.sessionsRevokedAt.getTime() / 1000)) {
    throw new UnauthorizedError('You were signed out. Please sign in again.');
  }
  res.locals.crmActor = { id: u.id, name: u.name, email: u.email } satisfies Actor;
}

/** The signed-in CRM member, as loaded by requireCrmAccess. */
export const actorOf = (res: Response): Actor => res.locals.crmActor as Actor;
