import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';

import { CaslAbilityFactory } from './casl-ability.factory';
import { ROLES_KEY } from './roles.decorator';

type AuthenticatedRequest = Request & { user?: { id?: number } };

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly caslAbilityFactory: CaslAbilityFactory,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const allowedRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!allowedRoles?.length) {
      return true;
    }

    const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
    const userId = request.user?.id;

    if (!userId) {
      throw new ForbiddenException('You do not have permission');
    }

    const grants = await this.caslAbilityFactory.getGrantsForUser(userId);
    const userRoles = grants.roles.map((role) => role.toLowerCase());

    const hasAllowedRole = allowedRoles.some((role) =>
      userRoles.includes(role.toLowerCase()),
    );

    if (!hasAllowedRole) {
      throw new ForbiddenException('You do not have permission');
    }

    return true;
  }
}
