import { createFileRoute } from "@tanstack/react-router";
import type {} from "@tanstack/react-start";
import { createClient } from "@supabase/supabase-js";

const BASE_URL = "https://biblewordoftheday.com";

interface SitemapEntry {
  path: string;
  lastmod?: string;
  changefreq?: "daily" | "weekly" | "monthly" | "yearly";
  priority?: string;
}

function admin() {
  return createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!, {
    auth: { autoRefreshToken: false, persistSession: false },
  });
}

async function fetchIndexableSlugs(): Promise<{ slug: string; updated_at: string | null }[]> {
  try {
    const sb = admin();
    const { data } = await sb
      .from("topics")
      .select("slug, updated_at, result_count")
      .eq("is_indexable", true)
      .gt("result_count", 0)
      .order("slug", { ascending: true });
    return (data ?? []).map((r: { slug: string; updated_at: string | null }) => ({
      slug: r.slug,
      updated_at: r.updated_at,
    }));
  } catch (e) {
    console.error("sitemap topics fetch failed", e);
    return [];
  }
}

async function fetchArchiveDates(): Promise<{ date: string }[]> {
  try {
    const sb = admin();
    const { data } = await sb
      .from("daily_devotionals")
      .select("date")
      .order("date", { ascending: false })
      .limit(500);
    return (data ?? []).map((r: { date: string }) => ({ date: String(r.date).slice(0, 10) }));
  } catch {
    return [];
  }
}

export const Route = createFileRoute("/sitemap.xml")({
  server: {
    handlers: {
      GET: async () => {
        const [topics, dates] = await Promise.all([fetchIndexableSlugs(), fetchArchiveDates()]);

        const entries: SitemapEntry[] = [
          { path: "/", changefreq: "daily", priority: "1.0" },
          { path: "/topics", changefreq: "weekly", priority: "0.8" },
          { path: "/archive", changefreq: "daily", priority: "0.6" },
          { path: "/about", changefreq: "yearly", priority: "0.4" },
          { path: "/privacy", changefreq: "yearly", priority: "0.2" },
          { path: "/terms", changefreq: "yearly", priority: "0.2" },
        ];

        for (const t of topics) {
          entries.push({
            path: `/topics/${t.slug}`,
            lastmod: t.updated_at ? t.updated_at.slice(0, 10) : undefined,
            changefreq: "weekly",
            priority: "0.8",
          });
        }
        for (const { date } of dates) {
          entries.push({
            path: `/daily-bible-word/${date}`,
            lastmod: date,
            changefreq: "monthly",
            priority: "0.7",
          });
        }

        const urls = entries.map((e) =>
          [
            `  <url>`,
            `    <loc>${BASE_URL}${e.path}</loc>`,
            e.lastmod ? `    <lastmod>${e.lastmod}</lastmod>` : null,
            e.changefreq ? `    <changefreq>${e.changefreq}</changefreq>` : null,
            e.priority ? `    <priority>${e.priority}</priority>` : null,
            `  </url>`,
          ].filter(Boolean).join("\n"),
        );
        const xml = [
          `<?xml version="1.0" encoding="UTF-8"?>`,
          `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`,
          ...urls,
          `</urlset>`,
        ].join("\n");
        return new Response(xml, {
          headers: { "Content-Type": "application/xml", "Cache-Control": "public, max-age=3600" },
        });
      },
    },
  },
});
