import { MetadataRoute } from "next";
import { getQuestions, getPatterns } from "@/lib/api";

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || "https://codetutor.example.com";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const entries: MetadataRoute.Sitemap = [
    {
      url: BASE_URL,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 1,
    },
    {
      url: `${BASE_URL}/questions`,
      lastModified: new Date(),
      changeFrequency: "daily",
      priority: 0.9,
    },
    {
      url: `${BASE_URL}/categories`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.8,
    },
    {
      url: `${BASE_URL}/patterns`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.8,
    },
  ];

  try {
    // Fetch all questions for individual pages
    const questionsResponse = await getQuestions({ limit: 1000 });
    for (const question of questionsResponse.items) {
      entries.push({
        url: `${BASE_URL}/questions/${question.slug}`,
        lastModified: new Date(),
        changeFrequency: "monthly",
        priority: 0.7,
      });
    }
  } catch {
    // Continue without question pages if API fails
  }

  try {
    // Fetch all patterns for individual pages
    const patternsResponse = await getPatterns();
    for (const pattern of patternsResponse.items) {
      entries.push({
        url: `${BASE_URL}/patterns/${pattern.slug}`,
        lastModified: new Date(),
        changeFrequency: "monthly",
        priority: 0.6,
      });
    }
  } catch {
    // Continue without pattern pages if API fails
  }

  return entries;
}
