import { CanActivate, ExecutionContext, Injectable, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { AuthUser } from '@vihar/shared';
import { REQUIRES_CAPTAIN_KEY } from '../decorators/auth.decorators';

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

  canActivate(ctx: ExecutionContext): boolean {
    const requiresCaptain = this.reflector.getAllAndOverride<boolean>(REQUIRES_CAPTAIN_KEY, [
      ctx.getHandler(),
      ctx.getClass(),
    ]);
    if (!requiresCaptain) return true;

    const req = ctx.switchToHttp().getRequest();
    const user = req.user as AuthUser | undefined;
    if (!user) throw new ForbiddenException('No user on request');
    if (!user.isCaptain && !user.isSuperAdmin) {
      throw new ForbiddenException('Captain role required');
    }
    return true;
  }
}
