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

/** @type {import('./$types').LayoutServerLoad} */
export async function load({ cookies, fetch, locals }) {
	const jwt = cookies.get('jwt');
	try {
		const response = await fetch(`${BASE_API_URI}/backend/users/all`, {
			credentials: 'include',
			headers: {
				Cookie: `jwt=${jwt}`
			}
		});
		if (!response.ok) {
			// Clear the invalid JWT cookie
			cookies.delete('jwt', { path: '/' });
			throw redirect(302, '/auth/login?next=admin/users/');
		}

		const data = await response.json();
		// Check if the server sent a new token
		const newToken = response.headers.get('Set-Cookie');
		refreshCookie(newToken, cookies);

		/** @type {App.Locals['users']}*/
		const users = data.users;

		users.forEach((user) => {
			userDatesFromRFC3339(user);
		});

		locals.users = users;
		return {
			subscriptions: locals.subscriptions,
			licence_categories: locals.licence_categories,
			users: locals.users,
			user: locals.user
		};
	} catch (error) {
		console.error('Error fetching data:', error);
		// In case of any error, clear the JWT cookie
		cookies.delete('jwt', { path: '/' });

		throw redirect(302, '/auth/login?next=admin/users/');
	}
}
