import { OAuth2Client } from 'google-auth-library';
import { AppError } from '../lib/utils';

export interface GoogleIdentity {
  googleId: string;
  email: string;
  emailVerified: boolean;
  firstName: string;
  lastName: string;
  avatarUrl?: string;
}

let client: OAuth2Client | null = null;

function getClient() {
  const clientId = process.env.GOOGLE_CLIENT_ID || process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
  if (!clientId) {
    throw new AppError('Google Sign-In is not configured', 503);
  }
  if (!client) {
    client = new OAuth2Client(clientId);
  }
  return { client, clientId };
}

export async function verifyGoogleIdToken(idToken: string): Promise<GoogleIdentity> {
  const { client, clientId } = getClient();

  let ticket;
  try {
    ticket = await client.verifyIdToken({
      idToken,
      audience: clientId,
    });
  } catch {
    throw new AppError('Invalid Google credential', 401);
  }

  const payload = ticket.getPayload();
  if (!payload?.sub || !payload.email) {
    throw new AppError('Google account is missing required profile data', 400);
  }

  if (payload.email_verified === false) {
    throw new AppError('Google email is not verified', 400);
  }

  const given = payload.given_name?.trim();
  const family = payload.family_name?.trim();
  const fullName = payload.name?.trim() || '';
  const [fallbackFirst, ...rest] = fullName.split(/\s+/).filter(Boolean);

  return {
    googleId: payload.sub,
    email: payload.email.toLowerCase(),
    emailVerified: true,
    firstName: given || fallbackFirst || 'Google',
    lastName: family || rest.join(' ') || 'User',
    avatarUrl: payload.picture,
  };
}
