import { cookies } from "next/headers";
import { cache } from "react";
import type { LanguageCode } from "@/types/language";
import { getLanguageCode, DEFAULT_LANGUAGE } from "@/types/language";
import { getSiteInfo } from "./data";

const LANGUAGE_COOKIE_NAME = "site-language";

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

/**
 * Sets the language cookie (server-side)
 * @param lang - Language code to set
 * @param hostname - Optional hostname to extract domain for subdomain support
 */
export async function setLanguage(lang: LanguageCode, hostname?: string): Promise<void> {
  const cookieStore = await cookies();
  
  // Extract root domain for cookie (e.g., "admin.example.com" -> ".example.com")
  // This allows cookies to work across subdomains
  let cookieDomain: string | undefined;
  if (hostname && hostname.includes(".")) {
    const parts = hostname.split(".");
    if (parts.length >= 2) {
      // Get root domain (last two parts, e.g., "example.com")
      const rootDomain = parts.slice(-2).join(".");
      cookieDomain = `.${rootDomain}`;
    }
  }
  
  const cookieOptions: any = {
    path: "/",
    maxAge: 60 * 60 * 24 * 365, // 1 year
    sameSite: "lax" as const,
    httpOnly: false, // Allow client-side access for language switching
    secure: process.env.NODE_ENV === 'production', // Use secure cookies in production (HTTPS)
  };
  
  // Set domain to allow cookies to work across subdomains
  if (cookieDomain && (process.env.NODE_ENV === 'production' || process.env.ALLOW_SUBDOMAIN_COOKIES === 'true')) {
    cookieOptions.domain = cookieDomain;
  }
  
  cookieStore.set(LANGUAGE_COOKIE_NAME, lang, cookieOptions);
}

/**
 * Gets language from request headers or cookies
 * Used in middleware and server components
 */
export function getLanguageFromRequest(
  cookieValue?: string | null,
  acceptLanguage?: string | null
): LanguageCode {
  // Priority: Cookie > Accept-Language header > Default
  if (cookieValue) {
    return getLanguageCode(cookieValue);
  }

  // Try to detect from Accept-Language header
  if (acceptLanguage) {
    const langs = acceptLanguage.toLowerCase().split(",");
    for (const lang of langs) {
      const code = lang.split(";")[0].trim().substring(0, 2);
      if (code === "en" || code === "pt" || code === "dk") {
        return code as LanguageCode;
      }
    }
  }

  return DEFAULT_LANGUAGE;
}

