import { createFileRoute } from "@tanstack/react-router";
import type {} from "@tanstack/react-start";
import { CONTENT_PAGES } from "@/lib/site-content";
import { listPosts } from "@/lib/blog.functions";

// TODO: replace with your project URL once a project name or custom domain is set.
const BASE_URL = "";

interface SitemapEntry {
  path: string;
  changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
  priority?: string;
  lastmod?: string;
}

export const Route = createFileRoute("/sitemap.xml")({
  server: {
    handlers: {
      GET: async () => {
        const entries: SitemapEntry[] = [
          { path: "/", changefreq: "weekly", priority: "1.0" },
          { path: "/welcome", changefreq: "monthly", priority: "0.9" },
          { path: "/gatamail", changefreq: "monthly", priority: "0.8" },
          { path: "/chatbud", changefreq: "monthly", priority: "0.8" },


          { path: "/about", changefreq: "monthly", priority: "0.9" },
          { path: "/contact", changefreq: "monthly", priority: "0.9" },
          { path: "/demo-request", changefreq: "monthly", priority: "0.9" },
          { path: "/blog", changefreq: "weekly", priority: "0.8" },
          { path: "/live-podcast", changefreq: "weekly", priority: "0.8" },
          { path: "/episodes", changefreq: "weekly", priority: "0.8" },
          { path: "/login", changefreq: "yearly", priority: "0.4" },
          { path: "/register", changefreq: "yearly", priority: "0.5" },
          { path: "/site-map", changefreq: "monthly", priority: "0.3" },
          ...CONTENT_PAGES.map((page) => ({
            path: page.slug,
            changefreq: (page.group === "Legal" ? "yearly" : "monthly") as SitemapEntry["changefreq"],
            priority: page.group === "Legal" ? "0.3" : "0.8",
          })),
        ];

        try {
          const { listEpisodes } = await import("@/lib/podcast.functions");
          for (const ep of await listEpisodes()) {
            entries.push({
              path: `/episodes/${ep.slug}`,
              changefreq: "monthly",
              priority: "0.7",
              lastmod: new Date(ep.published_at).toISOString(),
            });
          }
        } catch (error) {
          console.error("sitemap: could not load episodes", error);
        }

        try {
          const posts = await listPosts();
          for (const post of posts) {
            entries.push({
              path: `/blog/${post.slug}`,
              changefreq: "monthly",
              priority: "0.7",
              lastmod: post.published_at ? new Date(post.published_at).toISOString() : undefined,
            });
          }
        } catch (error) {
          console.error("sitemap: could not load blog posts", error);
        }

        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",
          },
        });
      },
    },
  },
});
