const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';

export function getGoogleAuthUrl(state: string): string {
	const params = new URLSearchParams({
		client_id: Bun.env.GOOGLE_CLIENT_ID!,
		redirect_uri: `${Bun.env.PUBLIC_SITE_URL}/auth/google/callback`,
		response_type: 'code',
		scope: 'openid email profile',
		state,
		access_type: 'online',
		prompt: 'select_account'
	});
	return `${GOOGLE_AUTH_URL}?${params.toString()}`;
}

export async function exchangeGoogleCode(
	code: string,
	redirectUri: string
): Promise<{
	access_token: string;
	token_type: string;
	expires_in: number;
	id_token: string;
	scope: string;
}> {
	const params = new URLSearchParams({
		client_id: Bun.env.GOOGLE_CLIENT_ID!,
		client_secret: Bun.env.GOOGLE_CLIENT_SECRET!,
		code,
		grant_type: 'authorization_code',
		redirect_uri: redirectUri
	});

	const response = await fetch(GOOGLE_TOKEN_URL, {
		method: 'POST',
		headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
		body: params.toString()
	});

	if (!response.ok) {
		const errText = await response.text();
		throw new Error(`Google token exchange failed: ${errText}`);
	}

	return await response.json();
}

/**
 * Decode Google's id_token JWT payload without signature verification.
 * Safe because the token is received directly from Google's token endpoint over TLS.
 */
export function decodeGoogleIdToken(idToken: string): {
	sub: string;
	email?: string;
	email_verified?: boolean;
	name?: string;
	given_name?: string;
	family_name?: string;
} {
	const [, payloadB64] = idToken.split('.');
	const padded = payloadB64 + '='.repeat((4 - (payloadB64.length % 4)) % 4);
	const payload = JSON.parse(atob(padded.replace(/-/g, '+').replace(/_/g, '/')));
	return payload;
}
