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

@Injectable()
export class GoogleAuthGuard extends AuthGuard('google') {
  private readonly logger = new Logger(GoogleAuthGuard.name);

  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      const result = (await super.canActivate(context)) as boolean;
      return result;
    } catch (err: any) {
      this.logger.error(`Google auth error: ${err.message}`, err.stack);
      throw err;
    }
  }

  handleRequest<T>(err: any, user: T, info: any): T {
    if (err) {
      this.logger.error(`Google handleRequest error: ${err.message || err}`);
      throw err;
    }
    if (!user) {
      this.logger.warn(`Google handleRequest: no user returned`);
      throw new UnauthorizedException('Google authentication failed');
    }
    return user;
  }
}
