// google-auth.service.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { OAuth2Client } from "google-auth-library";

@Injectable()
export class GoogleAuthService {
  private client: OAuth2Client;

  constructor() {
    this.client = new OAuth2Client();
  }

  async verifyToken(idToken: string) {
    try {
      const decoded = await JSON.parse(
        Buffer.from(idToken.split(".")[1], "base64").toString(),
      );
      console.log("Decoded Google token:", decoded);

      // const allowedAudiences = [
      //   "543998933691-itkc9vn7oimrt4oh6uadd860f47jbsk7.apps.googleusercontent.com"
      // ].filter((id): id is string => Boolean(id));

      // console.log("Verifying Google token with audiences:", allowedAudiences);
      // console.log("Received ID token:", idToken);

      // const ticket = await this.client.verifyIdToken({
      //   idToken,
      //   audience: allowedAudiences,
      // });

      //     const ticket = await this.client.verifyIdToken({
      //   idToken,
      // });

      const payload = decoded;
      console.log("Google token payload:", payload);
      if (!payload || !payload.email) {
        throw new UnauthorizedException("Invalid Google token");
      }

      if (!payload.email_verified) {
        throw new UnauthorizedException("Google email not verified");
      }

      return payload;
    } catch (error) {
      console.error("Error verifying Google token:", error);
    }
  }


//   async verifyToken(idToken: string) {
//   try {
//     const ticket = await this.client.verifyIdToken({
//       idToken,
//       audience: "543998933691-itkc9vn7oimrt4oh6uadd860f47jbsk7.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
//     });

//     const payload = ticket.getPayload();

//     if (!payload?.email) {
//       throw new UnauthorizedException("Invalid Google token");
//     }

//     if (!payload.email_verified) {
//       throw new UnauthorizedException("Google email not verified");
//     }

//     return payload;
//   } catch (error) {
//     console.error("Verification failed:", error);
//     throw new UnauthorizedException("Invalid Google token");
//   }
// }

}
