import { ExecutionContext, Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  private logger = new Logger('JwtAuthGuard');

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    this.logger.debug('Checking JWT authentication for request...');
    const request = context.switchToHttp().getRequest();

    // Check for Authorization header with Bearer token first
    const authHeader = request.headers['authorization'];

    if (authHeader && authHeader.startsWith('Bearer ')) {
      // Token is already in the right format in headers
      return super.canActivate(context);
    }

    // Fallback to checking cookies
    const cookie = request.cookies['Authentication'];

    if (!cookie) {
      throw new UnauthorizedException('Token not found in headers or cookies');
    }

    // Set the Authorization header with the token from cookie
    request.headers['authorization'] = `Bearer ${cookie}`;
    return super.canActivate(context);
  }
}
