/**
 * Server-only cookie utilities.
 * Import as: import { ... } from '@/lib/cookies/server'
 *
 * These functions use `next/headers` and must only be called from
 * Server Components, Server Actions, or Route Handlers — never from
 * client components or shared utility files.
 */
import { cookies } from 'next/headers';
import { COOKIE_NAMES, type CookieOptions } from './constants';

/**
 * Read a single cookie value from the incoming request.
 * Returns undefined when the cookie is absent or when called outside a
 * request context (e.g. build-time prerendering).
 */
export async function getServerCookie(name: string): Promise<string | undefined> {
  try {
    const store = await cookies();
    return store.get(name)?.value;
  } catch {
    return undefined;
  }
}

/**
 * Read the persisted color scheme from the request cookie and return the two
 * values the root layout needs:
 *
 *   colorScheme  — 'light' | 'dark' | undefined   for data-mui-color-scheme on <html>
 *   defaultMode  — 'light' | 'dark' | 'system'     for ThemeProvider's defaultMode
 *
 * When the cookie is absent (first ever visit), colorScheme is `undefined` so
 * the layout renders <html> WITHOUT a data-mui-color-scheme attribute at all —
 * tokens.css then falls through to its `@media (prefers-color-scheme: dark)`
 * block (scoped to the attribute being absent) for the very first paint,
 * with zero JS. defaultMode stays 'system' so MUI resolves the same OS
 * preference once it hydrates and stamps the attribute itself — CSS and MUI
 * agree, so there is nothing to visibly flip.
 * On all subsequent visits the stored value is used for both fields.
 */
export async function getThemeMode(): Promise<{
  colorScheme: 'light' | 'dark' | undefined;
  defaultMode: 'light' | 'dark' | 'system';
}> {
  const value = await getServerCookie(COOKIE_NAMES.COLOR_SCHEME);
  if (value === 'dark') return { colorScheme: 'dark', defaultMode: 'dark' };
  if (value === 'light') return { colorScheme: 'light', defaultMode: 'light' };
  return { colorScheme: undefined, defaultMode: 'system' };
}

/** @deprecated Use getThemeMode() instead */
export async function getColorSchemeCookie(): Promise<'light' | 'dark'> {
  const { colorScheme } = await getThemeMode();
  return colorScheme ?? 'light';
}

/**
 * Set a cookie via a Server Action or Route Handler response.
 *
 * NOTE: Cookies cannot be set from a Server Component's render function —
 * only from Server Actions (`'use server'`) or Route Handlers.
 * Call this inside a form action or API route, never during SSR render.
 */
export async function setServerCookie(
  name: string,
  value: string,
  options: CookieOptions = {},
): Promise<void> {
  const store = await cookies();
  store.set(name, value, options);
}
