import type {GetServerSideProps} from "next";

interface SitemapRoute {
    url: string;
    lastModified: string;
    changeFrequency?:
        | "always"
        | "hourly"
        | "daily"
        | "weekly"
        | "monthly"
        | "yearly"
        | "never";
    priority?: number;
}

const baseUrl = "https://dki.one";

export const getServerSideProps: GetServerSideProps = async () => {
    const staticRoutes: SitemapRoute[] = [
        {url: `${baseUrl}/`, lastModified: new Date().toISOString(), changeFrequency: "weekly", priority: 1.0},
        {
            url: `${baseUrl}/privacy-policy`,
            lastModified: new Date().toISOString(),
            changeFrequency: "yearly",
            priority: 0.3
        },
        {
            url: `${baseUrl}/legal-notice`,
            lastModified: new Date().toISOString(),
            changeFrequency: "yearly",
            priority: 0.3
        },
    ];

    try {
        const response = await fetch(`${baseUrl}/api/sitemap`);
        if (!response.ok) {
            console.error(`Failed to fetch dynamic sitemap: ${response.statusText}`);
        }

        const dynamicRoutes = (await response.json()) as SitemapRoute[];

        return {
            props: {
                sitemap: [...staticRoutes, ...dynamicRoutes],
            },
        };
    } catch (error) {
        console.error("Failed to fetch dynamic sitemap, using fallback:", error);

        return {
            props: {
                sitemap: staticRoutes,
            },
        };
    }
};

const generateXml = (routes: SitemapRoute[]): string => {
    const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
    const urlsetOpen = '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';
    const urlsetClose = '</urlset>';

    const urlEntries = routes
        .map(
            (route) => `
    <url>
      <loc>${route.url}</loc>
      <lastmod>${route.lastModified}</lastmod>
      ${route.changeFrequency ? `<changefreq>${route.changeFrequency}</changefreq>` : ""}
      ${route.priority ? `<priority>${route.priority}</priority>` : ""}
    </url>`
        )
        .join("");

    return `${xmlHeader}${urlsetOpen}${urlEntries}${urlsetClose}`;
};

const Sitemap = ({sitemap}: { sitemap: SitemapRoute[] }) => {
    const xmlSitemap = generateXml(sitemap);

    return new Response(xmlSitemap, {
        headers: {
            "Content-Type": "application/xml",
            "Cache-Control": "no-cache",
        },
    });
};

export default Sitemap;