import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { SCOPES_KEY } from '../decorators/scopes.decorator';
import { ApiKeyScope, Principal } from '../principal';

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

  canActivate(context: ExecutionContext): boolean {
    const principal: Principal | undefined = context.switchToHttp().getRequest().user;
    if (!principal || principal.type !== 'apiKey') {
      return true;
    }

    const required = this.reflector.getAllAndOverride<ApiKeyScope[] | undefined>(SCOPES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    const missing = (required ?? []).filter((s) => !principal.scopes.includes(s));
    if (missing.length > 0) {
      throw new ForbiddenException(`API key missing scope(s): ${missing.join(', ')}`);
    }
    return true;
  }
}
