import { NextResponse } from 'next/server';

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

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

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

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

export async function GET() {
  const visaDetails = await fetchvisadetails();

  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
  visaDetails.forEach((detail: Visas) => {
    const lastModDate = detail.created_at || detail.updated_at;
    const formattedDate = new Date(lastModDate).toISOString().split('T')[0];
    sitemap += `
      <url>
        <loc>${baseUrl}/visit-visa-detail/${detail.slug}</loc>
        <lastmod>${formattedDate}</lastmod>
        <priority>0.8</priority>
      </url>\n`;
  });

  sitemap += `</urlset>`;

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