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[]> => {
  try {
    // 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(),
      },
    ];

    // Check if running in build environment
    if (process.env.IS_BUILD) {
      console.log("Running in build mode - using mock data");
      const mockProjectsData: ProjectsData = {
        posts: [
          { slug: "project-1" },
          { slug: "project-2" },
          { slug: "project-3" },
        ],
      };
      const projectRoutes: SitemapRoute[] = mockProjectsData.posts.map(
        (project) => ({
          url: `${baseUrl}/projects/${project.slug}`,
          lastModified: new Date().toISOString(),
        }),
      );
      return [...staticRoutes, ...projectRoutes];
    }

    // Fetch project data from API
    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; // Return static pages instead of throwing an error
    }

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

    // Generate dynamic routes for projects
    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; // Return static pages in case of failure
  }
};

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 },
    );
  }
}
