import { NextResponse } from 'next/server';

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

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

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

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

export async function GET() {
  const alluniversities = await fetchUniversities();

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

  sitemap += `</urlset>`;

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