export interface SeoMetatagRecord {
  page_key: string;
  path: string;
  title: string;
  description: string;
  og_image: string | null;
  schema_type: 'organization' | 'service';
  service_name: string | null;
  service_desc: string | null;
}

let cachedSeoData: Record<string, SeoMetatagRecord> | null = null;
let cacheTimestamp = 0;
const CACHE_TTL_MS = 5 * 60 * 1000;

function getApiBaseUrl(requestUrl: string): string {
  const envUrl =
    (typeof process !== 'undefined' && process.env?.VITE_API_BASE_URL) ||
    (typeof import.meta !== 'undefined' && import.meta.env?.VITE_API_BASE_URL) ||
    '';

  if (envUrl) {
    return envUrl.replace(/\/+$/, '');
  }

  const url = new URL(requestUrl);
  return `${url.protocol}//${url.host}/api`;
}

export async function fetchAllSeoMeta(requestUrl: string): Promise<Record<string, SeoMetatagRecord>> {
  const now = Date.now();
  if (cachedSeoData && (now - cacheTimestamp) < CACHE_TTL_MS) {
    return cachedSeoData;
  }

  try {
    const apiBase = getApiBaseUrl(requestUrl);
    const res = await fetch(`${apiBase}/seo-metatags`, {
      headers: { Accept: 'application/json' },
    });

    if (!res.ok) {
      console.error(`[SEO] API returned ${res.status}`);
      return cachedSeoData ?? {};
    }

    const json = await res.json();
    if (json.status && json.data) {
      cachedSeoData = json.data;
      cacheTimestamp = now;
      return json.data;
    }
  } catch (err) {
    console.error('[SEO] Failed to fetch metatags:', err);
  }

  return cachedSeoData ?? {};
}

export async function fetchSeoForPage(pageKey: string, requestUrl: string): Promise<SeoMetatagRecord | null> {
  const all = await fetchAllSeoMeta(requestUrl);
  return all[pageKey] ?? null;
}
