import { cache } from "react";

import { API_BASE_URL, SERVER_API_HEADERS } from "@/lib/api/config";
import type { Language } from "@/lib/i18n/language";

/**
 * Server-only reads for the detail routes' `generateMetadata`.
 *
 * Native `fetch` with ISR and `SERVER_API_HEADERS`, wrapped in React `cache()`
 * — the same contract as the other `services/server.ts` modules, and for the
 * same reason: this must not pull in axios or Zustand (see CLAUDE.md on the two
 * API layers).
 *
 * **Only publicly readable endpoints are used.** A server render carries no
 * user token, so these four were checked against `routes/api.php` to confirm
 * they sit *outside* the `auth:api` group:
 *   - `opportunities/{id}/details/`      (line 113)
 *   - `learn-serve-opportunities/{id}/`  (line 117)
 *   - `events/{id}/`                     (line 230)
 *   - `public-profile/{user_id}/`        (line 64)
 * Anything behind auth would 401 here and is left without record-specific
 * metadata rather than guessed at.
 *
 * The cached response contains both language fields. Choose the requested
 * language after fetching, so the same public cache safely serves both.
 */

/** The only fields metadata needs. Everything is optional — a 404 or an error returns null. */
interface TitledRecord {
  title_en?: string | null;
  title_ar?: string | null;
  description_en?: string | null;
  description_ar?: string | null;
}

const REVALIDATE = 300;

async function fetchRecord(path: string): Promise<TitledRecord | null> {
  try {
    const response = await fetch(`${API_BASE_URL}${path}`, {
      next: { revalidate: REVALIDATE },
      headers: SERVER_API_HEADERS,
    });
    if (!response.ok) return null;
    const body = await response.json();
    // `key === "success"` matters: the API answers a rejected read with 200.
    if (body?.key !== "success") return null;
    return (body?.data ?? null) as TitledRecord | null;
  } catch {
    // Metadata must never break the page render.
    return null;
  }
}

export const fetchVolunteerOpportunityMeta = cache((id: string) =>
  fetchRecord(`/opportunities/${encodeURIComponent(id)}/details/`)
);

export const fetchLearnServeOpportunityMeta = cache((id: string) =>
  fetchRecord(`/learn-serve-opportunities/${encodeURIComponent(id)}/`)
);

export const fetchEventMeta = cache((id: string) =>
  fetchRecord(`/events/${encodeURIComponent(id)}/`)
);

/** Plain text, collapsed and clipped — descriptions are stored as HTML. */
export function metaDescription(
  record: TitledRecord | null,
  fallback: string,
  language: Language = "en"
): string {
  const raw = language === "ar" ? record?.description_ar || record?.description_en || "" : record?.description_en || record?.description_ar || "";
  const text = raw
    .replace(/<[^>]*>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
  if (!text) return fallback;
  return text.length > 160 ? `${text.slice(0, 157).trimEnd()}…` : text;
}

/** The record's title, or `fallback` when the read failed or returned nothing. */
export function metaTitle(record: TitledRecord | null, fallback: string, language: Language = "en"): string {
  return language === "ar" ? record?.title_ar || record?.title_en || fallback : record?.title_en || record?.title_ar || fallback;
}
