import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { getAppleAuthUrl } from '$lib/server/apple-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');

		// Store state + anonymousId in a short-lived cookie
		// sameSite 'none' + secure required because Apple POSTs cross-origin
		cookies.set('apple_oauth_state', JSON.stringify({ state, anonymousId }), {
			path: '/',
			httpOnly: true,
			secure: true,
			sameSite: 'none',
			maxAge: 600
		});

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