import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import type { Actions } from './$types';

export const actions = {
	default: async ({ cookies, fetch }) => {
		const sessionId = cookies.get('fa_session');

		// Best-effort backend logout: invalidates the server-side session row
		// and writes the LOGOUT audit entry. The client cookie is deleted
		// unconditionally below so a network failure here still logs the user out.
		if (sessionId) {
			try {
				const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
				await fetch(`${baseUrl}/api/auth/logout`, {
					method: 'POST',
					headers: { Cookie: `fa_session=${sessionId}` }
				});
			} catch (e) {
				console.error('Backend logout failed; clearing client cookie anyway', e);
			}
		}

		cookies.delete('fa_session', { path: '/' });
		// Also drop the legacy Basic-auth cookie in case a stale one lingers from before the migration.
		cookies.delete('auth_token', { path: '/' });

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