import { MetadataRoute } from 'next';
import { db } from '@/lib/db';
import { blogPosts as articles, customPages, homepageContent } from '@/shared/schema';
import { eq, and } from 'drizzle-orm';

export const dynamic = 'force-dynamic';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = 'https://ten-sura-game.com';
  
  // Get all active articles for THIS site only
  const allArticles = await db
    .select({
      slug: articles.slug,
      updatedAt: articles.updatedAt,
    })
    .from(articles)
    .where(
      and(
        eq(articles.isActive, true),
        eq(articles.siteId, 'ten-sura-game.com')
      )
    );
  
  // Static pages - Homepage
  const staticPages: MetadataRoute.Sitemap = [
    {
      url: baseUrl,
      lastModified: new Date(),
      changeFrequency: 'daily' as const,
      priority: 1.0,
    },
  ];

  // Fetch all custom pages and canvas data
  const allCustomPages = await db.select().from(customPages).where(eq(customPages.siteId, 'ten-sura-game.com'));
  const allCanvases = await db.select({ siteId: homepageContent.siteId, content: homepageContent.content, updatedAt: homepageContent.updatedAt }).from(homepageContent);
  const canvasMap = new Map(allCanvases.map(c => [c.siteId, c]));

  // Filter and map custom pages
  const dynamicCustomPages: MetadataRoute.Sitemap = allCustomPages
    .filter(page => {
      if (page.indexable === false) return false;
      const canvas = canvasMap.get(`/${page.slug}-ten-sura-game.com`);
      if (!canvas) return false;
      const blocks = (canvas.content as any)?.puckData?.content ?? [];
      return blocks.length > 0; // published = has at least one block
    })
    .map(page => {
      const canvas = canvasMap.get(`/${page.slug}-ten-sura-game.com`);
      return {
        url: `${baseUrl}/${page.slug}`,
        lastModified: canvas?.updatedAt ?? page.updatedAt ?? new Date(),
        changeFrequency: 'monthly' as const,
        priority: 0.6,
      };
    });
  
  // Category pages - 5 mobile gacha RPG strategy categories
  const categories = [
    '攻略情報',
    'キャラクター評価',
    'リセマラ・ガチャ情報',
    'イベント・アップデート',
    '初心者・育成ガイド',
  ];
  
  const categoryPages: MetadataRoute.Sitemap = categories.map((category) => ({
    url: `${baseUrl}/category/${encodeURIComponent(category)}`,
    lastModified: new Date(),
    changeFrequency: 'daily' as const,
    priority: 0.8,
  }));
  
  // Article pages - All active articles
  const articlePages: MetadataRoute.Sitemap = allArticles.map((article) => ({
    url: `${baseUrl}/post/${article.slug}`,
    lastModified: article.updatedAt || new Date(),
    changeFrequency: 'weekly' as const,
    priority: 0.6,
  }));
  
  return [...staticPages, ...dynamicCustomPages, ...categoryPages, ...articlePages];
}
