import "server-only";

import { after } from "next/server";

import { cmsOrigin, env } from "@/lib/env";

/**
 * The CMS issues preview links (docs/laravel-blog-api.md §12), but the
 * Symfony CMS doesn't refresh the website's cache after a change, so the
 * admin panel does it: see refreshWebsite().
 */

/**
 * Asks the website (SITE_URL/api/revalidate) to drop its cached blog pages,
 * so a change shows on the next visit instead of after its cache runs out.
 * Runs after the response is sent; a failure is only logged.
 */
export function refreshWebsite() {
  const { SITE_URL, REVALIDATE_SECRET } = env();
  if (!SITE_URL) return;
  after(async () => {
    try {
      const response = await fetch(`${SITE_URL}/api/revalidate`, {
        method: "POST",
        headers: REVALIDATE_SECRET
          ? { "x-revalidate-secret": REVALIDATE_SECRET }
          : {},
        signal: AbortSignal.timeout(10_000),
      });
      if (!response.ok)
        console.warn(`[site] refresh failed: HTTP ${response.status}`);
    } catch (error) {
      console.warn("[site] refresh failed", error);
    }
  });
}

/** Public path of an article on the website. */
export const blogPath = (slug: string) => `/blog/${slug}/`;

/** Makes root-relative upload URLs (e.g. "/uploads/…") absolute on the Laravel server. */
export function absoluteMediaUrl(url: string | null | undefined) {
  if (!url) return null;
  return url.startsWith("/") && !url.startsWith("//")
    ? `${cmsOrigin()}${url}`
    : url;
}
