import { building } from "$app/environment";
import apiFetch, { TOKEN_KEY, type CurrentUser } from "$lib/api";

export const ssr = false;
export const csr = true;
export const prerender = true;

export const load = async () => {
	const token = localStorage.getItem(TOKEN_KEY);
	let user: CurrentUser | null = null;
	if (token && !building) {
		try {
			user = await apiFetch<CurrentUser>("GET", "/api/current-user");
		} catch (e) {
			console.error("Could not fetch user from API: ", e);
			localStorage.removeItem(TOKEN_KEY);
		}
	}

	return { user: user?.user || null, guilds: user?.guilds || null };
};
