import { browser } from '$app/environment';
import { redirect } from '@sveltejs/kit';
import { clearTokens, getAccessToken, isJwtExpired, isValidJwtFormat } from '$lib/services/api';
import type { LayoutLoad } from './$types';

export const ssr = false;

export const load: LayoutLoad = async () => {
  if (!browser) {
    return { authenticated: false };
  }

  const token = getAccessToken();
  const isAuthenticated = Boolean(token && isValidJwtFormat(token) && !isJwtExpired(token));

  if (!isAuthenticated) {
    clearTokens();
    throw redirect(307, '/login');
  }

  return { authenticated: true };
};
