import { Request, Response, NextFunction } from 'express';
import { UserRole } from '@prisma/client';
import { AppError } from './error-handler';

export function requireRole(...roles: UserRole[]) {
  return (req: Request, _res: Response, next: NextFunction) => {
    if (!req.user) {
      throw new AppError(401, 'Authentication required', 'AUTH_REQUIRED');
    }

    // Check multi-role array (falls back to single role via auth middleware)
    const userRoles = req.user.roles || [req.user.role];

    // SUPER_ADMIN bypasses all role checks
    if (userRoles.includes(UserRole.SUPER_ADMIN)) {
      return next();
    }

    const hasRole = userRoles.some(r => roles.includes(r));

    if (!hasRole) {
      throw new AppError(403, 'Insufficient permissions', 'FORBIDDEN');
    }

    next();
  };
}

export function requireNonTemp(req: Request, _res: Response, next: NextFunction) {
  if (!req.user) {
    throw new AppError(401, 'Authentication required', 'AUTH_REQUIRED');
  }

  const userRoles = req.user.roles || [req.user.role];
  // User is "temp only" if their only role is TEMP
  if (userRoles.length === 1 && userRoles[0] === UserRole.TEMP) {
    throw new AppError(403, 'Temporary accounts cannot access this resource', 'TEMP_FORBIDDEN');
  }

  next();
}
