import type { MetadataRoute } from "next";
import { products, siteConfig } from "@/lib/site-config";
import { libraryProcedures } from "@/data/consentiq/library";
import { conditions as atlasConditions } from "@/data/atlas/conditions";
import { regions as atlasRegions } from "@/data/atlas/regions";
import { listPublishedCourses } from "@/lib/academy/queries";
import { listPublishedStudies } from "@/lib/research/queries";
import { listPublishedProducts } from "@/lib/store/queries";
import { listUnifiedPosts } from "@/lib/blog/unified";
import {
  listPublishedConditions as listPublishedAtlasConditions,
  listPublishedRegions as listPublishedAtlasRegions,
} from "@/lib/atlas/queries";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const now = new Date();
  const base = siteConfig.url;

  const staticEntries: MetadataRoute.Sitemap = [
    { url: `${base}/`,        lastModified: now, changeFrequency: "monthly", priority: 1.0 },
    { url: `${base}/about`,   lastModified: now, changeFrequency: "monthly", priority: 0.7 },
    { url: `${base}/team`,    lastModified: now, changeFrequency: "monthly", priority: 0.6 },
    { url: `${base}/clinical`,lastModified: now, changeFrequency: "monthly", priority: 0.6 },
    { url: `${base}/contact`, lastModified: now, changeFrequency: "yearly",  priority: 0.5 },
    { url: `${base}/join`,    lastModified: now, changeFrequency: "monthly", priority: 0.9 },
    { url: `${base}/login`,   lastModified: now, changeFrequency: "yearly",  priority: 0.3 },
    { url: `${base}/blog`,    lastModified: now, changeFrequency: "weekly",  priority: 0.6 },
    { url: `${base}/news`,    lastModified: now, changeFrequency: "daily",   priority: 0.6 },
    { url: `${base}/studies`, lastModified: now, changeFrequency: "daily",   priority: 0.6 },
    { url: `${base}/privacy`, lastModified: now, changeFrequency: "yearly",  priority: 0.2 },
    { url: `${base}/terms`,   lastModified: now, changeFrequency: "yearly",  priority: 0.2 },
    { url: `${base}/cookies`, lastModified: now, changeFrequency: "yearly",  priority: 0.2 },
    { url: `${base}/credits`, lastModified: now, changeFrequency: "yearly",  priority: 0.2 },
  ];

  const productEntries: MetadataRoute.Sitemap = products.map((p) => ({
    url: `${base}${p.href}`,
    lastModified: now,
    changeFrequency: "monthly",
    priority: 0.8,
  }));

  const consentIqLibrary: MetadataRoute.Sitemap = [
    {
      url: `${base}/products/consentiq/library`,
      lastModified: now,
      changeFrequency: "weekly",
      priority: 0.7,
    },
    ...libraryProcedures.map((p) => ({
      url: `${base}/products/consentiq/library/${p.slug}`,
      lastModified: now,
      changeFrequency: "monthly" as const,
      priority: 0.6,
    })),
  ];

  // Prefer DB-backed atlas content; fall back to TS seeds if the DB is down.
  const [dbAtlasRegions, dbAtlasConditions, allBlogPosts] = await Promise.all([
    listPublishedAtlasRegions().catch(() => [] as typeof atlasRegions),
    listPublishedAtlasConditions().catch(() => [] as typeof atlasConditions),
    listUnifiedPosts().catch(() => []),
  ]);
  const effRegions = dbAtlasRegions.length > 0 ? dbAtlasRegions : atlasRegions;
  const effConditions =
    dbAtlasConditions.length > 0 ? dbAtlasConditions : atlasConditions;

  const atlasEntries: MetadataRoute.Sitemap = [
    {
      url: `${base}/products/atlas/conditions`,
      lastModified: now,
      changeFrequency: "monthly",
      priority: 0.6,
    },
    {
      url: `${base}/products/atlas/regions`,
      lastModified: now,
      changeFrequency: "monthly",
      priority: 0.6,
    },
    ...effRegions.map((r) => ({
      url: `${base}/products/atlas/regions/${r.slug}`,
      lastModified: now,
      changeFrequency: "monthly" as const,
      priority: 0.5,
    })),
    ...effConditions.map((c) => ({
      url: `${base}/products/atlas/conditions/${c.slug}`,
      lastModified: now,
      changeFrequency: "monthly" as const,
      priority: 0.5,
    })),
  ];

  const blogEntries: MetadataRoute.Sitemap = allBlogPosts.map((p) => ({
    url: `${base}/blog/${p.slug}`,
    lastModified: p.modifiedAt ? new Date(p.modifiedAt) : p.date ? new Date(p.date) : now,
    changeFrequency: "monthly" as const,
    priority: 0.5,
  }));

  // Database-driven entries. If the DB is unreachable at build/render time
  // we degrade gracefully instead of failing the whole sitemap.
  const [courses, studies, storeProducts] = await Promise.all([
    listPublishedCourses().catch(() => []),
    listPublishedStudies().catch(() => []),
    listPublishedProducts().catch(() => []),
  ]);

  const academyEntries: MetadataRoute.Sitemap = [
    {
      url: `${base}/products/academy/courses`,
      lastModified: now,
      changeFrequency: "weekly",
      priority: 0.7,
    },
    ...courses.map((c) => ({
      url: `${base}/products/academy/courses/${c.slug}`,
      lastModified: now,
      changeFrequency: "monthly" as const,
      priority: 0.6,
    })),
  ];

  const researchEntries: MetadataRoute.Sitemap = [
    {
      url: `${base}/products/research/studies`,
      lastModified: now,
      changeFrequency: "weekly",
      priority: 0.6,
    },
    ...studies.map((s) => ({
      url: `${base}/products/research/studies/${s.slug}`,
      lastModified: now,
      changeFrequency: "monthly" as const,
      priority: 0.5,
    })),
  ];

  const storeEntries: MetadataRoute.Sitemap = storeProducts.map((p) => ({
    url: `${base}/products/store/${p.slug}`,
    lastModified: now,
    changeFrequency: "monthly",
    priority: 0.5,
  }));

  return [
    ...staticEntries,
    ...productEntries,
    ...consentIqLibrary,
    ...atlasEntries,
    ...blogEntries,
    ...academyEntries,
    ...researchEntries,
    ...storeEntries,
  ];
}
