import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy, VerifyCallback } from 'passport-google-oauth20';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(configService: ConfigService) {
    super({
      clientID:
        configService.get<string>('google.clientId', { infer: true }) || 'missing-google-client-id',
      clientSecret:
        configService.get<string>('google.clientSecret', { infer: true }) ||
        'missing-google-client-secret',
      callbackURL:
        configService.get<string>('google.callbackUrl', { infer: true }) ||
        'http://localhost:4000/api/v1/auth/google/callback',
      scope: ['email', 'profile'],
    });
  }

  validate(
    _accessToken: string,
    _refreshToken: string,
    profile: Profile,
    done: VerifyCallback,
  ): void {
    const email = profile.emails?.[0]?.value?.toLowerCase();

    if (!email) {
      done(new UnauthorizedException('Google account email is not available'));
      return;
    }

    done(null, {
      googleId: profile.id,
      email,
      name: profile.displayName ?? 'Google User',
      avatar: profile.photos?.[0]?.value,
    });
  }
}
