import { MetadataRoute } from "next";
import { getSiteUrl } from "@/seo/MetaSeo";

type CmsItem = {
    id: number;
    title: string;
    slug: string;
    url: string;
    lastmod?: string;
    type: "page" | "post";
};

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
    // -----------------------------
    // 1. Detect base URL dynamically
    // -----------------------------
    const baseUrl = await getSiteUrl();

    let cmsItems: CmsItem[] = [];

    try {
        // Fetch CMS sitemap data via POST request
        const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL || "https://cms.terralogic.in/oculus_be/wp-json/api/";
        const apiUrl = `${apiBase.endsWith("/") ? apiBase : apiBase + "/"}sitemap`;

        const response = await fetch(apiUrl, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            next: { revalidate: 60 },
        });

        if (response.ok) {
            const result = await response.json();
            if (result?.status && Array.isArray(result?.data)) {
                cmsItems = result.data;
            }
        }
    } catch (error) {
        console.error("Error fetching CMS sitemap items:", error);
    }

    // -----------------------------
    // 2. Map Dynamic CMS Items (Pages + Posts)
    // -----------------------------
    const dynamicUrls: MetadataRoute.Sitemap = cmsItems
        .filter((item) => item?.url && item?.slug)
        .map((item) => {
            // Strip domain & '/oculus_be' path prefix from WordPress URL
            const relativePath = item.url
                .replace(/^https?:\/\/[^/]+\/oculus_be/, "")
                .replace(/^https?:\/\/[^/]+/, "")
                .replace(/^\/+|\/+$/g, "");

            const fullUrl = relativePath ? `${baseUrl}/${relativePath}` : baseUrl;

            return {
                url: fullUrl,
                lastModified: item.lastmod ? new Date(item.lastmod) : new Date(),
                changeFrequency: item.type === "post" ? "weekly" : "daily",
                priority: relativePath === "" ? 1.0 : item.type === "page" ? 0.8 : 0.6,
            };
        });

    // -----------------------------
    // 3. Deduplicate URLs
    // -----------------------------
    const unique = new Map<string, MetadataRoute.Sitemap[number]>();

    dynamicUrls.forEach((item) => {
        const normalized = item.url.replace(/\/+$/, "") || baseUrl;
        if (!unique.has(normalized)) {
            unique.set(normalized, item);
        }
    });

    return Array.from(unique.values());
}