import { prisma } from '@tpmjs/db';
import type { MetadataRoute } from 'next';

/**
 * Dynamic sitemap that includes all pages and tools from the database
 * Automatically generated by Next.js at /sitemap.xml
 */
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = 'https://tpmjs.com';

  // Static pages with high priority
  const staticPages: MetadataRoute.Sitemap = [
    {
      url: baseUrl,
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },
    {
      url: `${baseUrl}/publish`,
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.8,
    },
    {
      url: `${baseUrl}/how-it-works`,
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.8,
    },
    {
      url: `${baseUrl}/spec`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.7,
    },
    {
      url: `${baseUrl}/sdk`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.7,
    },
    {
      url: `${baseUrl}/tool/tool-search`,
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 0.9,
    },
    {
      url: `${baseUrl}/playground`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.6,
    },
  ];

  // Fetch all tools from database
  // We only need package name and export name to build the URL, plus updatedAt for lastModified
  const tools = await prisma.tool.findMany({
    select: {
      package: {
        select: {
          npmPackageName: true,
          updatedAt: true,
        },
      },
      exportName: true,
      updatedAt: true,
    },
    orderBy: {
      updatedAt: 'desc',
    },
  });

  // Generate tool pages
  // URL format: /tool/[package-name]/[export-name]
  const toolPages: MetadataRoute.Sitemap = tools.map((tool) => {
    // Use the more recent of package or tool update time
    const lastModified =
      tool.updatedAt > tool.package.updatedAt ? tool.updatedAt : tool.package.updatedAt;

    return {
      url: `${baseUrl}/tool/${tool.package.npmPackageName}/${tool.exportName}`,
      lastModified,
      changeFrequency: 'weekly' as const,
      priority: 0.7,
    };
  });

  return [...staticPages, ...toolPages];
}
