import { createFileRoute } from "@tanstack/react-router";
import { supabase } from "@/lib/supabase";

export const Route = createFileRoute("/sitemap/xml")({
  loader: async () => {
    // Fetch all published news articles
    const { data: articles } = await supabase
      .from("news")
      .select("slug, published_at")
      .eq("published", true)
      .order("published_at", { ascending: false });

    // Build sitemap XML
    const baseUrl = "https://deadshotguild.name.ng";
    
    const staticPages: Array<{ loc: string; priority: string; changefreq: string; lastmod?: string }> = [
      { loc: "/", priority: "1.0", changefreq: "weekly" },
      { loc: "/news", priority: "0.9", changefreq: "weekly" },
      { loc: "/tournaments/history", priority: "0.8", changefreq: "weekly" },
      { loc: "/apply", priority: "0.7", changefreq: "monthly" },
      { loc: "/activate", priority: "0.6", changefreq: "monthly" },
    ];

    const newsPages = articles?.map((article: any) => ({
      loc: `/news/${article.slug}`,
      priority: "0.8",
      changefreq: "monthly",
      lastmod: article.published_at,
    })) || [];

    const allPages = [...staticPages, ...newsPages];

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${allPages.map(page => `
  <url>
    <loc>${baseUrl}${page.loc}</loc>
    ${page.lastmod ? `<lastmod>${page.lastmod.split('T')[0]}</lastmod>` : `<lastmod>${new Date().toISOString().split('T')[0]}</lastmod>`}
    <changefreq>${page.changefreq || 'monthly'}</changefreq>
    <priority>${page.priority || '0.5'}</priority>
  </url>
`).join('')}
</urlset>`;

    return new Response(xml, {
      headers: {
        "Content-Type": "application/xml",
        "Cache-Control": "public, max-age=3600",
      },
    });
  },
});
