import {NextResponse} from "next/server";

interface Project {
    slug: string;
    updated_at?: string; // Optional timestamp for last modification
}

interface ProjectsData {
    posts: Project[];
}

export const runtime = "nodejs"; // Force Node runtime

const GHOST_API_URL = "http://172.21.0.3:2368";
const GHOST_API_KEY = process.env.GHOST_API_KEY;

// Funktion, um die XML für die Sitemap zu generieren
function generateXml(sitemapRoutes: { url: string; lastModified: 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 = sitemapRoutes
        .map(
            (route) => `
    <url>
      <loc>${route.url}</loc>
      <lastmod>${route.lastModified}</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
    </url>`
        )
        .join("");

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

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

    // Statische Routen
    const staticRoutes = [
        {url: `${baseUrl}/`, lastModified: new Date().toISOString(), priority: 1, changeFreq: "weekly"},
        {url: `${baseUrl}/legal-notice`, lastModified: new Date().toISOString(), priority: 0.5, changeFreq: "yearly"},
        {url: `${baseUrl}/privacy-policy`, lastModified: new Date().toISOString(), priority: 0.5, changeFreq: "yearly"},
    ];

    try {
        const response = await fetch(
            `${GHOST_API_URL}/ghost/api/content/posts/?key=${GHOST_API_KEY}&limit=all`
        );
        if (!response.ok) {
            console.error(`Failed to fetch posts: ${response.statusText}`);
            return new NextResponse(generateXml(staticRoutes), {
                headers: {"Content-Type": "application/xml"},
            })
        }
        const projectsData = await response.json() as ProjectsData;
        const projects = projectsData.posts;

        // Dynamische Projekt-Routen generieren
        const sitemapRoutes = projects.map((project) => {
            const lastModified = project.updated_at || new Date().toISOString();
            return {
                url: `${baseUrl}/projects/${project.slug}`,
                lastModified,
                priority: 0.8,
                changeFreq: "monthly",
            };
        });

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

        // Rückgabe der Sitemap im XML-Format
        return new NextResponse(generateXml(allRoutes), {
            headers: {"Content-Type": "application/xml"},
        });

    } catch (error) {
        console.error("Failed to fetch posts from Ghost:", error);
        // Rückgabe der statischen Routen, falls Fehler auftritt
        return new NextResponse(generateXml(staticRoutes), {
            headers: {"Content-Type": "application/xml"},
        });
    }
}
