import type { Route } from "./+types/sitemap[.]xml";
import { getRecentBlogPosts, getProjectItems } from "~/sanity/client";

export async function loader({ request }: Route.LoaderArgs) {
  const baseUrl = "https://visworks365.com"; // Update with your actual domain
  
  // Fetch all dynamic content
  const [posts, projects] = await Promise.all([
    getRecentBlogPosts(100), // Get more posts for sitemap
    getProjectItems(100), // Get more projects for sitemap
  ]);

  const staticPages = [
    {
      url: baseUrl,
      changefreq: "daily",
      priority: 1.0,
      lastmod: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/about-us`,
      changefreq: "monthly",
      priority: 0.8,
      lastmod: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/services`,
      changefreq: "monthly",
      priority: 0.9,
      lastmod: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/projects`,
      changefreq: "weekly",
      priority: 0.9,
      lastmod: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/blog`,
      changefreq: "daily",
      priority: 0.9,
      lastmod: new Date().toISOString(),
    },
    {
      url: `${baseUrl}/schedule`,
      changefreq: "monthly",
      priority: 0.7,
      lastmod: new Date().toISOString(),
    },
  ];

  const blogPages = posts.map((post: any) => ({
    url: `${baseUrl}/blog/${post.slug.current}`,
    changefreq: "monthly",
    priority: 0.7,
    lastmod: post.publishedDate || new Date().toISOString(),
  }));

  const projectPages = projects.map((project: any) => ({
    url: `${baseUrl}/projects/${project.slug.current}`,
    changefreq: "monthly",
    priority: 0.8,
    lastmod: project.endDate || new Date().toISOString(),
  }));

  const allPages = [...staticPages, ...blogPages, ...projectPages];

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${allPages
  .map(
    (page) => `  <url>
    <loc>${page.url}</loc>
    <lastmod>${page.lastmod}</lastmod>
    <changefreq>${page.changefreq}</changefreq>
    <priority>${page.priority}</priority>
  </url>`
  )
  .join("\n")}
</urlset>`;

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