import { NextResponse } from "next/server";
import ApiServerService from "@core/Services/Api.Server.Service";
import { PublicServicesResults } from "@models/Service.model";
import { sliderFrames } from "@core/app/Services/SliderFrames";

export async function GET() {
    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://turnosxpress.com.ar";

    interface SitemapImage {
        url: string;
        title: string;
        caption: string;
    }

    interface SitemapRoute {
        url: string;
        lastModified?: string;
        changeFrequency: string;
        priority: number;
        images?: SitemapImage[];
    }

    // Static routes (lastModified omitted to avoid faking it to Google)
    const staticRoutes: SitemapRoute[] = [
        {
            url: `${baseUrl}`,
            changeFrequency: "daily",
            priority: 1.0,
            images: sliderFrames.map((frame) => ({
                url: `${baseUrl}${frame.image}`,
                title: frame.title,
                caption: frame.description,
            })),
        },
        {
            url: `${baseUrl}/landing/find`,
            changeFrequency: "daily",
            priority: 0.8,
        },
        {
            url: `${baseUrl}/landing/login`,
            changeFrequency: "monthly",
            priority: 0.5,
        },
        {
            url: `${baseUrl}/landing/signup`,
            changeFrequency: "monthly",
            priority: 0.5,
        },
        {
            url: `${baseUrl}/landing/offer-appointments`,
            changeFrequency: "weekly",
            priority: 0.9,
        },
        {
            url: `${baseUrl}/landing/pricing`,
            changeFrequency: "weekly",
            priority: 0.9,
        },
    ];

    let serviceRoutes: SitemapRoute[] = [];

    try {
        let currentPage = 1;
        let totalPages = 1;

        do {
            // Fetch public services with pagination
            const servicesResult = await ApiServerService.post<PublicServicesResults>("services/search", {
                page: currentPage,
                limit: 1000,
            });

            if (servicesResult && servicesResult.data) {
                totalPages = servicesResult.pages || 1;
                
                const newRoutes = servicesResult.data.map((service) => ({
                    url: `${baseUrl}/landing/service/${service.id}`,
                    changeFrequency: "weekly",
                    priority: 0.8,
                    images: [
                        {
                            url: service.image.startsWith("http")
                                ? service.image
                                : `${process.env.NEXT_PUBLIC_API_URL}${service.image}`,
                            title: service.name,
                            caption: service.description,
                        },
                    ],
                }));
                
                serviceRoutes = [...serviceRoutes, ...newRoutes];
            } else {
                break;
            }
            
            currentPage++;
        } while (currentPage <= totalPages);
        
    } catch (error) {
        console.error("Error generating sitemap:", error);
    }

    const allRoutes = [...staticRoutes, ...serviceRoutes];

    const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
    ${allRoutes
            .map((route) => {
                return `
    <url>
        <loc>${route.url}</loc>
        ${route.lastModified ? `<lastmod>${route.lastModified}</lastmod>` : ""}
        <changefreq>${route.changeFrequency}</changefreq>
        <priority>${route.priority}</priority>
        ${route.images
                        ? route.images
                            .map(
                                (img) => `
        <image:image>
            <image:loc>${img.url}</image:loc>
            <image:title><![CDATA[${img.title}]]></image:title>
            <image:caption><![CDATA[${img.caption}]]></image:caption>
        </image:image>`
                            )
                            .join("")
                        : ""
                    }
    </url>`;
            })
            .join("")}
</urlset>`;

    return new NextResponse(sitemapXml, {
        headers: {
            "Content-Type": "application/xml",
        },
    });
}
