import { Request, Response, NextFunction } from 'express';
import type { Permission } from '../lib/permissions';
import { ForbiddenError, UnauthorizedError } from '../lib/errors';

/** Allow the request only if the user's effective permissions include ALL of `needed`. */
export function requirePermission(...needed: Permission[]) {
  return (req: Request, _res: Response, next: NextFunction): void => {
    if (!req.user) throw new UnauthorizedError();
    const ok = needed.every((p) => req.user!.perms.includes(p));
    if (!ok) throw new ForbiddenError(`Requires permission: ${needed.join(', ')}`);
    next();
  };
}

/** Allow the request if the user's effective permissions include ANY of `options`. */
export function requireAnyPermission(...options: Permission[]) {
  return (req: Request, _res: Response, next: NextFunction): void => {
    if (!req.user) throw new UnauthorizedError();
    if (!options.some((p) => req.user!.perms.includes(p))) throw new ForbiddenError(`Requires permission: one of ${options.join(', ')}`);
    next();
  };
}
