import { NextResponse } from 'next/server';

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

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

const PAGE_SLUG =  '/best-study-abroad-consultants'

async function fetchData(): Promise<Data[]> {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/api/frontend/sitemap/getsilodetailroutes/${PAGE_SLUG}`, {
        method: "POST"
    });
    const data = await response.json();

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

export async function GET() {
  const completeData = await fetchData();

  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`;

  sitemap += `
    <url>
      <loc>${baseUrl}/best-study-abroad-consultants</loc>
      <lastmod>${new Date().toISOString().split('T')[0]}</lastmod>
      <priority>1.0</priority>
    </url>\n`;

  // Add Universities
  completeData.forEach((data: Data) => {
    const lastModDate = data.created_at || data.updated_at;
    const formattedDate = new Date(lastModDate).toISOString().split('T')[0];
    sitemap += `
      <url>
        <loc>${baseUrl}/best-study-abroad-consultants/${data.slug}</loc>
        <lastmod>${formattedDate}</lastmod>
        <priority>0.8</priority>
      </url>\n`;
  });

  sitemap += `</urlset>`;

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