import type { Metadata } from "next";
import { cache } from "react";
import { fetchSiteRouteMetadata, type MetadataValues, type PublicRouteMetadata } from "@roottale/cms-client/server";
import { buildPageMetadata } from "@roottale/cms-renderer-next/routes";

/** Pages and sitemap can reuse this locale snapshot; Next fetch caching survives render boundaries. */
export const loadSiteRouteMetadata = cache((locale = "ko") => fetchSiteRouteMetadata({
  apiKey: process.env.ROOTTALE_API_KEY!, baseUrl: process.env.ROOTTALE_API_BASE,
  locale, revalidate: 300,
}));

/** fallback은 계약 manifest와 같은 사이트 정의에서 가져온다. API key는 서버 전용이다. */
export async function routeMetadata(
  routeKey: string,
  options: { canonical: string; fallback: MetadataValues; contractChecksum: string; forceNoindex?: boolean },
): Promise<Metadata> {
  let route: PublicRouteMetadata | null = null;
  try {
    const snapshot = await loadSiteRouteMetadata();
    route = snapshot.routes.find((entry) => entry.routeKey === routeKey) ?? null;
    if (route && route.path !== new URL(options.canonical).pathname) {
      console.error("메타데이터 공개 경로 불일치", { routeKey });
      route = null;
    }
  } catch (error) {
    // 오류를 "설정 없음"으로 저장하는 별도 캐시를 만들지 않는다.
    console.error("메타데이터 조회 실패", { routeKey, error: error instanceof Error ? error.name : "unknown" });
  }
  return buildPageMetadata({
    ...route,
    fallback: options.fallback,
    // noindexReasons를 포함한 공통 정책을 보존하며 직접 false로 강제 차단을 풀지 않는다.
    robots: { ...route?.robots, forceNoindex: options.forceNoindex || route?.robots?.forceNoindex },
  }, {
    canonical: options.canonical,
    verification: {
      routeKey, locale: route?.locale ?? "ko", version: route?.version,
      contractChecksum: options.contractChecksum,
    },
  });
}
