import { NextRequest, NextResponse } from 'next/server';
import { getLatestArticles, getTrendingArticles, getAuthorInfo, getLatestAuthorData, getFeaturedArticle, getFeaturedArticles, getAllCategories, getCategoryArticles } from '@/lib/utils/db';

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const type = searchParams.get('type');
  const countStr = searchParams.get('count');
  const count = countStr ? parseInt(countStr, 10) : 5;

  try {
    let data: any = null;

    if (type === 'latest') {
      data = await getLatestArticles(count);
    } else if (type === 'trending') {
      data = await getTrendingArticles(count);
    } else if (type === 'featured') {
      data = await getFeaturedArticle();
    } else if (type === 'featured-list') {
      data = await getFeaturedArticles(count);
    } else if (type === 'latest-author') {
      data = await getLatestAuthorData();
    } else if (type === 'categories-with-articles') {
      const cats = await getAllCategories();
      data = await Promise.all(
        cats.map(async (cat) => {
          const dbArticles = await getCategoryArticles(cat.japanese || cat.slug, count);
          return {
            categoryName: cat.japanese || cat.slug,
            articles: dbArticles.map(a => ({
              title: a.title,
              image: a.cardImage || '',
              linkUrl: `/post/${a.slug}`,
            })),
          };
        })
      );
    } else {
      return NextResponse.json({ error: 'Invalid data type' }, { status: 400 });
    }

    return NextResponse.json({ data });
  } catch (error) {
    console.error('Error fetching editor preview data:', error);
    return NextResponse.json({ error: 'Failed to fetch preview data' }, { status: 500 });
  }
}
