import type { APIRoute } from "astro";
import { getProductsFromDB, getBrandsFromDB, getModelsByBrand } from "../lib/products";

export const GET: APIRoute = async () => {
  const baseUrl = "https://sneakerpicks.nl";
  const staticPages = ["", "/sneakers", "/merken", "/deals", "/zoeken"];

  const products = await getProductsFromDB({ limit: 50000 });
  const brands = await getBrandsFromDB();

  // Get models per brand
  const brandModels: { brandSlug: string; modelSlug: string }[] = [];
  for (const brand of brands) {
    try {
      const models = await getModelsByBrand(brand.slug);
      for (const model of models) {
        brandModels.push({ brandSlug: brand.slug, modelSlug: model.slug });
      }
    } catch {}
  }

  const today = new Date().toISOString().split("T")[0];

  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  xml += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;

  for (const page of staticPages) {
    xml += `  <url>\n    <loc>${baseUrl}${page}</loc>\n    <lastmod>${today}</lastmod>\n    <changefreq>daily</changefreq>\n    <priority>${page === "" ? "1.0" : "0.8"}</priority>\n  </url>\n`;
  }

  for (const brand of brands) {
    xml += `  <url>\n    <loc>${baseUrl}/merken/${brand.slug}</loc>\n    <lastmod>${today}</lastmod>\n    <changefreq>weekly</changefreq>\n    <priority>0.7</priority>\n  </url>\n`;
  }

  for (const bm of brandModels) {
    xml += `  <url>\n    <loc>${baseUrl}/merken/${bm.brandSlug}/${bm.modelSlug}</loc>\n    <lastmod>${today}</lastmod>\n    <changefreq>weekly</changefreq>\n    <priority>0.65</priority>\n  </url>\n`;
  }

  for (const product of products) {
    xml += `  <url>\n    <loc>${baseUrl}/sneakers/${product.slug}</loc>\n    <lastmod>${today}</lastmod>\n    <changefreq>daily</changefreq>\n    <priority>0.6</priority>\n  </url>\n`;
  }

  xml += `</urlset>`;

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