// routes/sitemap.js

const express = require("express");
const router = express.Router();
const { createClient } = require("@supabase/supabase-js");

const supabase = createClient(
  "https://your-project-id.supabase.co", // Replace with your Supabase URL
  "your-anon-or-service-key" // Replace with your Supabase key (use service key for backend)
);

router.get("/sitemap.xml", async (req, res) => {
  res.header("Content-Type", "application/xml");

  const { data: therapists, error } = await supabase
    .from("therapists") // Replace with your actual table name
    .select("slug, name, image");

  if (error) {
    return res.status(500).send("Error fetching data");
  }

  const urlEntries = therapists
    .map(
      (t) => `
  <url>
    <loc>https://theralink.online/therapist/${t.slug}</loc>
    <lastmod>${new Date().toISOString().split("T")[0]}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
    <image:image>
      <image:loc>https://theralink.online/images/therapists/${t.image}</image:loc>
      <image:title>${t.name} - Licensed Therapist</image:title>
    </image:image>
  </url>`
    )
    .join("");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  ${urlEntries}
</urlset>`;

  res.send(xml);
});

module.exports = router;
