/**
 * Server-side reads of the public CMS API for the website.
 *
 * Calls go straight to API_ORIGIN (not through the /api/v1 rewrite) and are cached:
 * the region and language come from the URL, so the same URL always shows the same
 * content and can be prerendered. Published home page changes appear within seconds
 * (HOME_CACHE below); the region list refreshes every minute.
 */
import { cacheLife, cacheTag } from "next/cache";
import { API_ORIGIN } from "@/lib/apiOrigin";
import { normalizeContent, type HomeSection, type PublicHomePage, type PublicRegion } from "./content";
import type { PublicPage, PublicServicePage, ServiceList } from "./pageContent";
import type { ArticleCategoryList, ArticleList, ArticlePageData } from "./articles";
import type { ProductList, ProductPageData } from "./products";
import { FALLBACK_REGIONS } from "./regions";

/** `quiet404`: a 404 is an expected answer (unknown slug), not worth a warning. */
async function getJson<T>(path: string, { quiet404 = false } = {}): Promise<T | null> {
  try {
    const res = await fetch(`${API_ORIGIN}/api/v1${path}`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(8000) });
    if (!res.ok) {
      if (!(quiet404 && res.status === 404)) console.warn(`[cms] GET ${path} → ${res.status}`);
      return null;
    }
    return ((await res.json()) as { data: T }).data;
  } catch (err) {
    console.warn(`[cms] GET ${path} failed:`, err instanceof Error ? err.message : err);
    return null;
  }
}

/** Active regions with their languages (GET /public/regions). Falls back to the snapshot above. */
export async function getRegions(): Promise<PublicRegion[]> {
  "use cache";
  cacheLife("minutes");
  cacheTag("cms:regions");
  const regions = await getJson<PublicRegion[]>("/public/regions");
  return regions?.length ? regions : FALLBACK_REGIONS;
}

/**
 * Home page cache lifetime (seconds).
 * - revalidate 5: after 5 s, the next visit triggers a background refresh and the
 *   visit after that shows the new content, so a publish appears within seconds.
 * - expire 1 h and stale 30 s keep the page prerendered. With expire under 5 minutes
 *   or stale under 30 s, Next would skip prerendering and call the API on every visit.
 *   `stale` only affects in-app link clicks; a full reload never uses it.
 */
const HOME_CACHE = { stale: 30, revalidate: 5, expire: 3600 };

/**
 * The published home page for one region and language, or null when the API is
 * unreachable or serves a different region than asked for. The page then shows its
 * built-in content, so a URL never shows another region's content.
 *
 * The API currently decides the region from the caller's IP and uses `region` only
 * when the IP country is unknown, so from a server it serves the server's region.
 * Until the backend treats `region` as authoritative, only that region (normally
 * Global) gets CMS content; the others log a mismatch here.
 */
export async function getHomePage(region: string, lang: string): Promise<PublicHomePage | null> {
  "use cache";
  cacheLife(HOME_CACHE);
  cacheTag("cms:home", `cms:home:${region}:${lang}`);
  const data = await getJson<PublicHomePage>(`/public/home-page?region=${encodeURIComponent(region)}&lang=${encodeURIComponent(lang)}`);
  if (!data) return null;
  if (data.region?.code !== region) {
    console.warn(`[cms] asked for region "${region}" but the API served "${data.region?.code}"; showing built-in content`);
    return null;
  }
  return {
    ...data,
    sections: (data.sections ?? []).map((s) => ({ ...s, content: normalizeContent(s.content, s.key) }) as HomeSection),
  };
}

/**
 * Inner page cache lifetime (seconds). Same as HOME_CACHE except `stale`.
 * Inner pages have no URL params, so with partialPrefetching their whole content must
 * be in the route's App Shell, and the App Shell only includes cached data whose
 * `stale` is at least 5 minutes. With a shorter `stale`, dev flags every inner page as
 * a "Blocking Route" (uncached data during prerendering).
 * Publishing from the admin expires the tag at once (app/(admin)/_lib/siteCache.ts), so
 * the next full load shows the change. A visitor already browsing the site (link clicks,
 * no reload) may see a page up to 5 minutes old. revalidate 5 is the fallback when
 * content changes without going through the admin editor.
 */
const PAGE_CACHE = { stale: 300, revalidate: 5, expire: 3600 };

/**
 * A published inner page (GET /public/pages/:key), or null when the API is unreachable
 * or nothing on the page is published yet. The page then shows its built-in content.
 *
 * Inner pages are global and English (no region or language in their URL). `lang` is
 * always sent: without it the API answers in the default language of the region it
 * detects from the caller's IP, which for these server-side calls is the server's.
 */
export async function getPage(key: string, lang = "en"): Promise<PublicPage | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:pages", `cms:page:${key}`);
  const data = await getJson<PublicPage>(`/public/pages/${encodeURIComponent(key)}?lang=${encodeURIComponent(lang)}`);
  if (!data?.sections?.length) return null;
  return { ...data, sections: data.sections.map((s) => ({ ...s, content: normalizeContent(s.content) })) };
}

/* ------------------------------------------------------------------ */
/* Services ("Read More" pages)                                        */
/* ------------------------------------------------------------------ */

/**
 * Published services by Services page division (GET /public/services), or null when the
 * API is unreachable. Cached like the inner pages; the admin expires "cms:services" when
 * a service changes on the website.
 */
export async function getServiceList(lang = "en"): Promise<ServiceList | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:services");
  const data = await getJson<ServiceList>(`/public/services?lang=${encodeURIComponent(lang)}`);
  return data ? normalizeContent(data) : null;
}

/** True once at least one service is published: from then on the CMS decides which services exist. */
export const hasPublishedServices = (list: ServiceList | null) => !!list?.divisions.some((d) => d.services.length > 0);

/** One published service (GET /public/services/:slug), or null (unknown, not on the website, or the API is down). */
export async function getServicePage(slug: string, lang = "en"): Promise<PublicServicePage | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:services", `cms:service:${slug}`);
  const data = await getJson<PublicServicePage>(`/public/services/${encodeURIComponent(slug)}?lang=${encodeURIComponent(lang)}`, { quiet404: true });
  if (!data) return null;
  return { ...data, card: normalizeContent(data.card), sections: (data.sections ?? []).map((s) => ({ ...s, content: normalizeContent(s.content) })) };
}

/* ------------------------------------------------------------------ */
/* Products                                                            */
/* ------------------------------------------------------------------ */

/**
 * The product list (GET /public/products) for a query string built by productQuery(),
 * or null when the API is unreachable. The catalogue's first, unfiltered page is
 * rendered on the server from this; filtering happens in the browser.
 */
export async function getProducts(query = "", lang = "en"): Promise<ProductList | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:products");
  const data = await getJson<ProductList>(`/public/products?lang=${encodeURIComponent(lang)}${query ? `&${query}` : ""}`);
  return data ? normalizeContent(data) : null;
}

/**
 * One product page (GET /public/products/:slug), or null when it isn't on the website
 * (or the API is down). An old slug answers 301 and fetch follows it: the result's
 * `slug` is then the current one, and the page redirects there.
 */
export async function getProduct(slug: string, lang = "en"): Promise<ProductPageData | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:products", `cms:product:${slug}`);
  const data = await getJson<ProductPageData>(`/public/products/${encodeURIComponent(slug)}?lang=${encodeURIComponent(lang)}`, { quiet404: true });
  return data ? normalizeContent(data) : null;
}

/* ------------------------------------------------------------------ */
/* Articles                                                            */
/* ------------------------------------------------------------------ */

/**
 * The article categories (filter tabs) with their counts, or null when the API is
 * unreachable. The admin expires "cms:articles" when an article or category changes.
 */
export async function getArticleCategories(lang = "en"): Promise<ArticleCategoryList | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:articles");
  return getJson<ArticleCategoryList>(`/public/article-categories?lang=${encodeURIComponent(lang)}`);
}

/** A page of article cards (GET /public/articles), or null when the API is unreachable. */
export async function getArticles(query = "", lang = "en"): Promise<ArticleList | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:articles");
  const data = await getJson<ArticleList>(`/public/articles?lang=${encodeURIComponent(lang)}${query ? `&${query}` : ""}`);
  return data ? normalizeContent(data) : null;
}

/**
 * One article (GET /public/articles/:slug), or null when it isn't on the website (or the
 * API is down). An old slug answers 301 and fetch follows it: the result's `slug` is then
 * the current one, and the page redirects there.
 */
export async function getArticle(slug: string, lang = "en"): Promise<ArticlePageData | null> {
  "use cache";
  cacheLife(PAGE_CACHE);
  cacheTag("cms:articles", `cms:article:${slug}`);
  const data = await getJson<{ article: ArticlePageData }>(`/public/articles/${encodeURIComponent(slug)}?lang=${encodeURIComponent(lang)}`, { quiet404: true });
  return data?.article ? normalizeContent(data.article) : null;
}
