import { NextResponse } from 'next/server';

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

interface Courses {
  university_slug: string;
  slug: string;
  created_at?: string;
  updated_at: string;
}

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

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

export async function GET() {
  const courses = await fetchCourses();

  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
  courses.forEach((course: Courses) => {

    sitemap += `
      <url>
        <loc>${baseUrl}/${course.university_slug}/${course.slug}</loc>
        <priority>0.8</priority>
      </url>\n`;
  });

  sitemap += `</urlset>`;

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