import { getCachedSitemap } from "@/services/wp";

const URL = process.env.SITE_URL;

function generateSiteMap(pages: Array<any>) {
  return `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
     <url>
       <loc>${URL}</loc>
     </url>
     ${pages
       .map(({ link }: { link: string }) => {
         return `
           <url>
               <loc>${link}</loc>
           </url>
         `;
       })
       .join("")
       .trim()}
    </urlset>`.trim();
}

export async function GET() {
  const sitemapUrls: Array<any> = await getCachedSitemap();
  const body = generateSiteMap(sitemapUrls);

  return new Response(body, {
    status: 200,
    headers: {
      "Cache-control": "public, s-maxage=86400, stale-while-revalidate",
      "content-type": "application/xml",
    },
  });
}
