import { kratosServerClient } from '$lib/kratos-server';
import { redirect } from '@sveltejs/kit';
import { PUBLIC_KRATOS_URL } from '$env/static/public';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ url, request }) => {
	const flowId = url.searchParams.get('flow');
	const code = url.searchParams.get('code');

	// If no flow ID, redirect to Kratos to create the flow (with proper CSRF cookie handling)
	if (!flowId) {
		throw redirect(303, `${PUBLIC_KRATOS_URL}/self-service/verification/browser`);
	}

	// Load the existing flow
	const cookie = request.headers.get('cookie') || undefined;
	let flow;

	try {
		const result = await kratosServerClient.getVerificationFlow({ id: flowId, cookie });
		flow = result.data;
	} catch (error: any) {
		// If flow is expired/invalid, redirect to create a new one
		if ([410, 403, 400].includes(error?.status || error?.response?.status)) {
			throw redirect(303, `${PUBLIC_KRATOS_URL}/self-service/verification/browser`);
		}
		throw error;
	}

	// If we have a valid flow and code, auto-submit the verification
	if (flow && code) {
		try {
			const result = await kratosServerClient.updateVerificationFlow({
				flow: flow.id,
				updateVerificationFlowBody: {
					method: 'code',
					code: code
				},
				cookie // Pass session cookie so Kratos can associate verification with authenticated user
			});

			// Verification code submitted successfully
			// Check if Kratos wants us to redirect somewhere
			if (result.data && (result.data as any).redirect_browser_to) {
				throw redirect(303, (result.data as any).redirect_browser_to);
			}

			// Otherwise redirect to home
			throw redirect(303, '/');
		} catch (error: any) {
			// Re-throw if this is a redirect (SvelteKit internal)
			if (error?.status === 303 || error?.location) {
				throw error;
			}

			console.error('Auto verification failed:', error);

			// If Kratos returned an updated flow with error messages, use it
			if (error.response?.data?.ui) {
				flow = error.response.data;
			} else {
				// Add a user-friendly error message to the flow UI
				if (!flow.ui.messages) {
					flow.ui.messages = [];
				}
				flow.ui.messages.push({
					id: 4070001,
					text: 'The verification code has expired or is invalid. Please request a new verification email by entering your email address below.',
					type: 'error',
					context: {}
				});
			}
		}
	}

	return { flow };
};
