import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { PUBLIC_KRATOS_URL } from '$env/static/public';

export const POST: RequestHandler = async ({ cookies, fetch, request }) => {
	const formData = await request.formData();
	const returnTo = formData.get('return_to')?.toString() || 'https://account.example.com';
	
	try {
		const sessionToken = cookies.get('ory_kratos_session');

		if (sessionToken) {
			// Create a logout flow through Oathkeeper with return_to parameter
			const logoutUrl = new URL(`${PUBLIC_KRATOS_URL}/self-service/logout/browser`);
			logoutUrl.searchParams.set('return_to', returnTo);
			
			const response = await fetch(logoutUrl.toString(), {
				method: 'GET',
				headers: {
					cookie: `ory_kratos_session=${sessionToken}`
				},
				redirect: 'manual'
			});

			// Get the logout token from response
			if (response.status === 200) {
				const data = await response.json();
				if (data.logout_url) {
					// Execute logout - this will redirect to return_to after logout
					await fetch(data.logout_url, {
						method: 'GET',
						headers: {
							cookie: `ory_kratos_session=${sessionToken}`
						}
					});
				}
			}
		}

		// Clear cookie on the server side with matching attributes
		cookies.delete('ory_kratos_session', {
			path: '/',
			domain: '.example.com'
		});
	} catch (error) {
		console.error('Logout error:', error);
		// Continue to redirect even if logout fails
	}

	// Redirect to the return_to URL or default to login page
	if (returnTo && returnTo !== 'https://account.example.com') {
		throw redirect(303, returnTo);
	}

	throw redirect(303, '/login');
};
