import { OAuth2Client } from "google-auth-library";
import { env } from "../env";

const client = new OAuth2Client(env.googleClientId);

export interface GoogleProfile {
  email: string;
  name: string | null;
  emailVerified: boolean;
}

export async function verifyGoogleIdToken(idToken: string): Promise<GoogleProfile> {
  const ticket = await client.verifyIdToken({
    idToken,
    audience: env.googleClientId,
  });
  const payload = ticket.getPayload();
  if (!payload?.email) {
    throw new Error("Google token payload is missing an email");
  }
  return {
    email: payload.email.toLowerCase(),
    name: payload.name ?? null,
    emailVerified: payload.email_verified ?? false,
  };
}
