import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic'; // ✅ Fix: Forces this route to be dynamic

interface Guides {
  slug: string;
  created_at?: string;
  updated_at: string;
}

async function fetchguides(): Promise<Guides[]> {
  try {
    const guideResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/api/frontend/sitemap/getallguides`, {
        method: "POST"
    });
    const data = await guideResponse.json();

    return data?.data || []; // Access the universities array
  } catch (error) {
    console.error("Error fetching guides:", error);
    return [];
  }
}

export async function GET() {
  const guides = await fetchguides();

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL_DOMAIN || 'https://yourwebsite.com';

  let sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  sitemap += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;

  // Add Universities
  guides.forEach((guide: Guides) => {
    const lastModDate = guide.created_at || guide.updated_at;
    const formattedDate = new Date(lastModDate).toISOString().split('T')[0];
    sitemap += `
      <url>
        <loc>${baseUrl}/guides/${guide.slug}</loc>
        <lastmod>${formattedDate}</lastmod>
        <priority>0.8</priority>
      </url>\n`;
  });

  sitemap += `</urlset>`;

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