import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext().req;
    console.log('[GqlAuthGuard] Extracted request:', {
      hasRequest: !!request,
      hasHeaders: !!request?.headers,
      authorization: request?.headers?.authorization?.substring(0, 30),
    });
    return request;
  }

  handleRequest(err: any, user: any, info: any) {
    console.log('[GqlAuthGuard] handleRequest:', {
      hasError: !!err,
      hasUser: !!user,
      userId: user?.userId,
      info,
    });

    if (err || !user) {
      throw err || new UnauthorizedException('GraphQL authentication failed');
    }
    return user;
  }
}
