import { NextResponse } from "next/server";

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

interface ProjectsData {
  posts: Project[];
}

interface SitemapRoute {
  url: string;
  lastModified: string;
}

const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://dki.one";

const generateSitemap = async (): Promise<SitemapRoute[]> => {
  // Static pages
  const staticRoutes: SitemapRoute[] = [
    { url: `${baseUrl}/`, lastModified: new Date().toISOString() },
    {
      url: `${baseUrl}/privacy-policy`,
      lastModified: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/legal-notice`,
      lastModified: new Date().toISOString(),
    },
  ];

  try {
    console.log("Fetching project data from API...");
    const response = await fetch(`${baseUrl}/api/fetchAllProjects`, {
      headers: { "Cache-Control": "no-cache" },
    });

    if (!response.ok) {
      console.error(`Failed to fetch projects: ${response.statusText}`);
      return staticRoutes; // Fallback auf statische Seiten
    }

    const projectsData = (await response.json()) as ProjectsData;
    console.log("Fetched project data:", projectsData);

    // Dynamische Projekt-Routen generieren
    const projectRoutes: SitemapRoute[] = projectsData.posts.map((project) => ({
      url: `${baseUrl}/projects/${project.slug}`,
      lastModified: project.updated_at
        ? new Date(project.updated_at).toISOString()
        : new Date().toISOString(),
    }));

    return [...staticRoutes, ...projectRoutes];
  } catch (error) {
    console.error("Failed to generate sitemap:", error);
    return staticRoutes; // Fallback nur auf statische Seiten
  }
};

export async function GET() {
  try {
    const sitemap = await generateSitemap();
    return NextResponse.json(sitemap, {
      headers: { "Cache-Control": "no-cache" },
    });
  } catch (error) {
    console.error("Failed to generate sitemap:", error);
    return NextResponse.json(
      { error: "Failed to generate sitemap" },
      { status: 500 },
    );
  }
}
