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

/** The roles a bug tracker account can have (the super admin aside). */
export const TRACKER_ROLES = [Role.QA, Role.DEVELOPER] as const;
export type TrackerRole = (typeof TRACKER_ROLES)[number];

const ALLOWED: Role[] = [Role.SUPER_ADMIN, ...TRACKER_ROLES];

/** The signed-in member, as loaded by requireBugAccess. */
export interface BugActor {
  id: string;
  name: string;
  role: Role;
}

/**
 * The bug tracker's door: the super admin, QA and developers only, and only
 * while the account is switched on and the session predates no "sign out
 * everywhere". Checked against the database on every request, like the CRM's
 * and the blog's, so switching an account off ends its access at once.
 */
export function requireBugAccess(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 (!ALLOWED.includes(req.user.role)) throw new ForbiddenError('The bug tracker is for the QA and development team.');
  const u = await prismaUnscoped.user.findUnique({
    where: { id: req.user.sub },
    select: { id: true, name: true, role: true, deactivatedAt: true, sessionsRevokedAt: true },
  });
  if (!u || u.deactivatedAt) throw new UnauthorizedError('This account has been switched off.');
  // The role in the token is the role the session was opened with: a changed
  // role signs the person out (updateMember), so the two always agree here.
  if (u.role !== req.user.role) throw new UnauthorizedError('Your access changed. Please sign in again.');
  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.bugActor = { id: u.id, name: u.name, role: u.role } satisfies BugActor;
}

/**
 * BT6: who a change is credited to when GitHub made it and no member of the
 * team could be matched to the commit or pull request. Not an account: nobody
 * can sign in as it, and it is never told about anything.
 */
export const GITHUB_ACTOR: BugActor = { id: 'github', name: 'GitHub', role: Role.SUPER_ADMIN };

export const bugActorOf = (res: Response): BugActor => res.locals.bugActor as BugActor;

/** Only the super admin manages the team and the settings. */
export function requireSuperAdmin(req: Request, _res: Response, next: NextFunction): void {
  if (req.user?.role !== Role.SUPER_ADMIN) {
    next(new ForbiddenError('Only the super admin can do this.'));
    return;
  }
  next();
}
