import { lexend } from '@/app/fonts';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { AppShell } from '@/components/crm/AppShell';
import { SESSION_COOKIE } from '@/config/constants';
import { ServerUnavailable } from '@/components/crm/ServerUnavailable';
import { ToastProvider } from '@/components/crm/ToastProvider';
import { CurrentUserProvider } from '@/features/auth/CurrentUser';
import { getMyProfile } from '@/features/settings/api.server';
import { UserPrefsProvider } from '@/features/settings/UserPrefs';
import { isApiError } from '@/lib/api/errors';
import '@/styles/crm-app.css';
import { getMeOnceMore, isServerTrouble, meErrorCode } from '@/lib/auth/load-me';

/** Authenticated CRM shell (sidebar + topbar) for companies and future CRM pages. */
export default async function AppLayout({ children }: { children: React.ReactNode }) {
  // Loaded here so the first render has the user's date format and time zone, beside `/me` so the
  // page doesn't wait for one after the other. A failed load doesn't stop the page:
  // UserPrefsProvider tries again from the browser.
  const profileLoad = getMyProfile().catch(() => null);
  let me;
  try {
    me = await getMeOnceMore();
  } catch (err) {
    if (isApiError(err) && err.isUnauthenticated) {
      // A session cookie the API no longer accepts: the session expired (QA #585). No cookie at
      // all is a plain first visit, which gets no message.
      const hadSession = Boolean((await cookies()).get(SESSION_COOKIE)?.value);
      redirect(hadSession ? '/login?error=session_expired' : '/login');
    }
    // HUB-746 (940): the server's trouble says nothing about the session. Stay on this address
    // and offer to try again, rather than send a signed-in user to the login page.
    if (isServerTrouble(err)) return <ServerUnavailable />;
    redirect(`/login?error=${meErrorCode(err)}`);
  }

  if (!me.onboarding.completed) {
    redirect('/onboarding/role');
  }

  const profile = await profileLoad;

  return (
    <div className={lexend.className}>
      <CurrentUserProvider key={me.business.id} me={me}>
        <UserPrefsProvider initialProfile={profile}>
          <ToastProvider>
            <AppShell me={me}>{children}</AppShell>
          </ToastProvider>
        </UserPrefsProvider>
      </CurrentUserProvider>
    </div>
  );
}
