import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import Papa from "papaparse";
import { SITE_URL } from "@/utils/staticValues";

export async function GET() {
  const csvPath = path.join(process.cwd(), "/public/data/", "site-map.csv");
  const csvFile = fs.readFileSync(csvPath, "utf8");

  const parsed = Papa.parse(csvFile, {
    header: true,
    skipEmptyLines: true,
  });

  const baseUrl = SITE_URL;
  const urls = parsed.data as { slug: string }[];
  console.log(urls);

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  ${urls
    .map(({ slug }) => {
      return `<url>
                <loc>${SITE_URL}/${slug === "home" ? "" : slug}</loc>
                <changefreq>monthly</changefreq>
                <priority>0.8</priority>
            </url>`;
    })
    .join("\n")}
</urlset>`;

  return new NextResponse(sitemap, {
    headers: {
      "Content-Type": "application/xml",
    },
  });
}
