import {NextResponse} from "next/server";

export const dynamic = 'force-dynamic';

export async function GET() {
    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL;
    const apiUrl = `${baseUrl}/api/sitemap`; // Verwende die vollständige URL zur API

    // In test runs, allow returning a mocked sitemap explicitly
    if (process.env.NODE_ENV === 'test' && process.env.GHOST_MOCK_SITEMAP) {
        // For tests return a simple object so tests can inspect `.body`
        if (process.env.NODE_ENV === 'test') {
            return { body: process.env.GHOST_MOCK_SITEMAP, headers: { "Content-Type": "application/xml" } } as any;
        }
        return new NextResponse(process.env.GHOST_MOCK_SITEMAP, { headers: { "Content-Type": "application/xml" } });
    }

    try {
        // Holt die Sitemap-Daten von der API
        // Try global fetch first, then fall back to node-fetch
        let res: any;
        try {
            if (typeof (globalThis as any).fetch === 'function') {
                res = await (globalThis as any).fetch(apiUrl);
            }
        } catch (e) {
            res = undefined;
        }

        if (!res || typeof res.ok === 'undefined' || !res.ok) {
            try {
                const mod = await import('node-fetch');
                const nodeFetch = (mod as any).default ?? mod;
                res = await nodeFetch(apiUrl);
            } catch (err) {
                console.error('Error fetching sitemap:', err);
                return new NextResponse("Error fetching sitemap", {status: 500});
            }
        }

        if (!res || !res.ok) {
            console.error(`Failed to fetch sitemap: ${res?.statusText ?? 'no response'}`);
            return new NextResponse("Failed to fetch sitemap", {status: 500});
        }

        const xml = await res.text();

        // Gibt die XML mit dem richtigen Content-Type zurück
        return new NextResponse(xml, {
            headers: {"Content-Type": "application/xml"},
        });
    } catch (error) {
        console.error("Error fetching sitemap:", error);
        return new NextResponse("Error fetching sitemap", {status: 500});
    }
}
