import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';

/**
 * JWT Authentication Guard
 *
 * This guard:
 * - Uses the JWT strategy to authenticate requests
 * - Checks for valid JWT token in Authorization header
 * - Attaches user object to request if authentication succeeds
 * - Can be bypassed with @Public() decorator
 *
 * Usage:
 * @UseGuards(JwtAuthGuard)
 * @Get('protected')
 * protectedRoute(@CurrentUser() user: UserPayload) {
 *   return { user };
 * }
 */
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  /**
   * Determine if the route should be accessible without authentication
   * Routes decorated with @Public() will bypass this guard
   */
  canActivate(context: ExecutionContext) {
    // Check if route is marked as public
    const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    // Otherwise, perform JWT authentication
    return super.canActivate(context);
  }
}
