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 './blog-posts.service';

const BLOG_ROLES: Role[] = [Role.SUPER_ADMIN, Role.CONTENT_EDITOR];

/**
 * The blog's door: the super admin and content editors 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,
 * so switching an editor off ends their access at once.
 */
export function requireBlogAccess(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 (!BLOG_ROLES.includes(req.user.role)) throw new ForbiddenError('The blog is for the platform team.');
  const u = await prismaUnscoped.user.findUnique({
    where: { id: req.user.sub },
    select: { id: true, name: 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.blogActor = { id: u.id, name: u.name } satisfies Actor;
}

/** The signed-in writer, as loaded by requireBlogAccess. */
export const blogActorOf = (res: Response): Actor => res.locals.blogActor as Actor;

/** Only the super admin manages the writers. */
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 manage blog writers.'));
    return;
  }
  next();
}
