import { ForbiddenException, Injectable } from '@nestjs/common';
import { initializeApp } from 'firebase-admin/app';
import { Auth, getAuth } from 'firebase-admin/auth';
import { GoogleAuthPayload } from './interfaces/google-auth-payload.interface';
import Joi from 'joi';
import { GoogleAuthConfigService } from '../../../config/authentication/google-auth/config.service';

@Injectable()
export class GoogleAuthService {
  private _auth: Auth;

  constructor(
    private readonly _googleAuthConfigService: GoogleAuthConfigService,
  ) {
    const firebaseApp = initializeApp({
      projectId: this._googleAuthConfigService.projectId,
    });

    this._auth = getAuth(firebaseApp);
  }

  async verify(idToken: string) {
    try {
      const {
        uid: googleId,
        email,
        email_verified: isEmailVerified,
      } = await this._auth.verifyIdToken(idToken);

      const payload: GoogleAuthPayload = {
        googleId,
        email,
        isEmailVerified,
      };

      const schema = Joi.object({
        googleId: Joi.string().required(),
        email: Joi.string().email().required(),
        isEmailVerified: Joi.boolean().required(),
      });

      await schema.validateAsync(payload);

      return payload;
    } catch {
      throw new ForbiddenException();
    }
  }
}
