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

export const Roles = Reflector.createDecorator<string[]>();

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

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get(Roles, context.getHandler());
    if (!requiredRoles) {
      return true; // No role required
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user || !user.role) {
      throw new ForbiddenException('Zugriff verweigert - Keine Rolle gesetzt');
    }

    if (!requiredRoles.includes(user.role)) {
      throw new ForbiddenException(
        `Zugriff verweigert - Erforderliche Rolle(n): ${requiredRoles.join(', ')}`
      );
    }

    return true;
  }
}
