import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
  Type,
  UnauthorizedException,
} from '@nestjs/common';
import { hasPassengerPermission } from './passenger-permission.util';

export function PassengerPermissionGuard(permissions: string[]): Type<CanActivate> {
  @Injectable()
  class PassengerPermissionsGuard implements CanActivate {
    canActivate(context: ExecutionContext): boolean {
      const request = context.switchToHttp().getRequest<{ user?: any }>();
      const user = request.user;

      if (!permissions?.length) return true;
      if (!user) throw new UnauthorizedException('Authentication required');

      if (permissions.some((p) => hasPassengerPermission(user, p))) return true;

      throw new ForbiddenException(
        `Missing permission. Required one of: ${permissions.join(', ')}`,
      );
    }
  }

  return PassengerPermissionsGuard;
}
