import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
  Type,
  UnauthorizedException,
} from '@nestjs/common';
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';

import { hasFreightPermission } from './freight-permission.util';

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

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

      if (permissions.some((p) => hasFreightPermission(user, p))) {
        return true;
      }

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

  return FreightPermissionsGuard;
}
