import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { getGoogleAuthUrl } from '$lib/server/google-auth';

export const actions: Actions = {
	default: async ({ cookies, request }) => {
		const data = await request.formData();
		const anonymousId = data.get('anonymousId')?.toString() || '';

		// Generate CSRF state
		const stateBytes = crypto.getRandomValues(new Uint8Array(16));
		const state = Buffer.from(stateBytes).toString('base64url');

		// sameSite 'lax' is safe here because Google sends a GET redirect back
		// (unlike Apple which POSTs cross-origin, requiring 'none')
		cookies.set('google_oauth_state', JSON.stringify({ state, anonymousId }), {
			path: '/',
			httpOnly: true,
			secure: true,
			sameSite: 'lax',
			maxAge: 600
		});

		redirect(302, getGoogleAuthUrl(state));
	}
};
