import { cookies } from "next/headers";
import { cache } from "react";
import type { ThemeId } from "@/types/theme";
import { getThemeId, DEFAULT_THEME } from "@/types/theme";
import { getSiteInfo } from "./data";

const THEME_COOKIE_NAME = "site-theme";

/**
 * Gets the current theme (server-side)
 * Priority: Site-wide default (siteinfo.json) > User cookie > DEFAULT_THEME
 * Uses React cache to avoid multiple reads per request
 */
export const getTheme = cache(async (): Promise<ThemeId> => {
  // First, check site-wide default theme from siteinfo.json
  const siteInfo = getSiteInfo();
  if (siteInfo.defaultTheme) {
    return getThemeId(siteInfo.defaultTheme);
  }
  
  // Fallback to user's cookie preference (if they have one)
  const cookieStore = await cookies();
  const themeCookie = cookieStore.get(THEME_COOKIE_NAME);
  if (themeCookie?.value) {
    return getThemeId(themeCookie.value);
  }
  
  // Final fallback to default
  return DEFAULT_THEME;
});

/**
 * Gets theme from request headers or cookies
 * Used in middleware and server components
 */
export function getThemeFromRequest(
  cookieValue?: string | null
): ThemeId {
  // Priority: Cookie > Default
  if (cookieValue) {
    return getThemeId(cookieValue);
  }

  return DEFAULT_THEME;
}

