"use server";

/**
 * Tells the website that a CMS page changed, so it shows the change on the next visit.
 *
 * The admin publishes straight to the CMS API, so Next.js never sees the change itself.
 * Without this call the website waits for its cache to time out (app/(site)/_lib/cms.ts):
 * the first visit after a publish still shows the old content.
 *
 * updateTag expires the page's cached data now, so the next request waits for fresh
 * content, and it clears this browser's client router cache.
 *
 * Server Actions are public endpoints, so the caller must send a valid admin token.
 * Otherwise anyone could clear the cache over and over and send every visit to the API.
 */
import { updateTag } from "next/cache";
import { API_ORIGIN } from "@/lib/apiOrigin";
import { INNER_PAGE_KEYS } from "./cms";

const PAGE_KEYS = new Set<string>(["home", ...INNER_PAGE_KEYS]);

/** True when the token belongs to a signed-in admin (the API accepts it on an admin endpoint). */
async function isAdmin(accessToken: string): Promise<boolean> {
  if (!accessToken) return false;
  const res = await fetch(`${API_ORIGIN}/api/v1/admin/pages`, {
    headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}` },
    cache: "no-store",
    signal: AbortSignal.timeout(8000),
  }).catch(() => null);
  return !!res?.ok;
}

export async function refreshSitePage(pageKey: string, accessToken: string): Promise<boolean> {
  if (!PAGE_KEYS.has(pageKey) || !(await isAdmin(accessToken))) return false;
  // Tags set in app/(site)/_lib/cms.ts. The home page tag covers every region and language.
  updateTag(pageKey === "home" ? "cms:home" : `cms:page:${pageKey}`);
  return true;
}

/**
 * Same for services (the Services page cards, the list and every /services/<slug>),
 * articles (Thought Leadership list and /articles/<slug>) and products (the catalogue on /global-agriculture and every /products/<slug>). Catalog
 * list changes (category names, certifications…) show on product pages too, so they
 * refresh "products".
 */
export async function refreshSiteContent(kind: "services" | "products" | "articles", accessToken: string): Promise<boolean> {
  if (!(await isAdmin(accessToken))) return false;
  if (kind === "services") {
    updateTag("cms:services");
    updateTag("cms:page:services");
  } else if (kind === "products") {
    updateTag("cms:products");
  } else {
    // The Thought Leadership list, its tabs and every /articles/<slug>.
    updateTag("cms:articles");
  }
  return true;
}
