import { BASE_API_URI } from '$lib/utils/constants';
import { fail, redirect } from '@sveltejs/kit';

/** @type {import('./$types').PageServerLoad} */
export async function load({ locals }) {
	// redirect user if not logged in
	if (!locals.user) {
		throw redirect(302, `/auth/login?next=/`);
	}
}

/** @type {import('./$types').Actions} */
export const actions = {
	default: async ({ fetch, cookies }) => {
		/** @type {RequestInit} */
		const requestInitOptions = {
			method: 'POST',
			credentials: 'include',
			headers: {
				'Content-Type': 'application/json',
				Cookie: `jwt=${cookies.get('jwt')}`
			}
		};

		const res = await fetch(`${BASE_API_URI}/backend/logout/`, requestInitOptions);

		if (!res.ok) {
			const response = await res.json();
			const errors = [];
			errors.push({ error: response.error, id: 0 });
			return fail(400, { errors: errors });
		}

		// eat the cookie
		cookies.delete('jwt', { path: '/' });

		// The server should clear the cookie, so we don't need to handle it here
		// Just check if the cookie is cleared in the response
		const setCookieHeader = res.headers.get('set-cookie');
		if (!setCookieHeader || !setCookieHeader.includes('jwt=;')) {
			console.error('JWT cookie not cleared in response');
			return fail(500, {
				errors: [
					{
						error: 'Server error: Failed to clear authentication token',
						id: Date.now()
					}
				]
			});
		}
		// redirect the user
		throw redirect(302, '/auth/login');
	}
};
