import { authFetchStatus, isAuthRedirectError } from '../api.js';
import { updateNav } from './layout.js';

window.addEventListener('unhandledrejection', (ev) => {
  if (isAuthRedirectError(ev.reason)) {
    ev.preventDefault();
  }
});

/**
 * @param {{ needsAdmin?: boolean, activeNav?: string }} opts
 * @returns {Promise<object|null>} Session-Status oder null bei Redirect
 */
export async function guard(opts = {}) {
  const { needsAdmin = false, activeNav = '' } = opts;
  let st;
  try {
    st = await authFetchStatus();
  } catch {
    st = { needsBootstrap: false, loggedIn: false, user: null };
  }
  if (st.needsBootstrap) {
    if (!location.pathname.endsWith('/bootstrap.html')) {
      location.href = '/bootstrap.html';
      return null;
    }
    return st;
  }
  if (!st.loggedIn) {
    if (!location.pathname.endsWith('/login.html')) {
      location.href = '/login.html';
      return null;
    }
    return st;
  }
  if (
    location.pathname.endsWith('/login.html') ||
    location.pathname.endsWith('/bootstrap.html')
  ) {
    location.href = '/start.html';
    return null;
  }
  if (needsAdmin && st.user?.role !== 'admin') {
    location.href = '/start.html';
    return null;
  }
  updateNav(st, activeNav);
  return st;
}
