import { NextResponse } from "next/server";
import { FetchData } from "@/libs/api";
import { localhostdomain, WorkDomain } from "@/app/domain";

// Handle the GET request
export async function GET(req, { params }) {
  try {
    // Get the param from the route params (e.g., 'en-sitemap.xml')
    const { param } = params;

    // Get the domain from headers or default to empty
    const host = req.headers.get("host") || "";
    const isLocalhost = host.includes(localhostdomain);
    const domain = isLocalhost ? WorkDomain : host;
    const baseUrl = `https://${domain}`;
    const parameters = param.replace(".xml", "");
    const sitemapData = await FetchData(domain, parameters);
    if (!sitemapData) {
      return NextResponse.json({ error: "Sitemap not found" }, { status: 404 });
    }

    // Generate the XML for the specific sitemap
    const pages = sitemapData.urls.map((page) => ({
      loc: `${baseUrl}/${page.url}`,
      lastmod: new Date().toISOString(), // You can replace this with actual lastmod dates
    }));

    const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
      ${pages
        .map(
          ({ loc, lastmod }) => `
        <url>
          <loc>${loc}</loc>
          <lastmod>${lastmod}</lastmod>
        </url>
      `
        )
        .join("")}
    </urlset>`;

    // Return the generated sitemap as XML
    return new NextResponse(sitemap, {
      status: 200,
      headers: {
        "Content-Type": "text/xml",
      },
    });
  } catch (error) {
    console.error("Error generating sitemap:", error);
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 }
    );
  }
}
