// API Routes for Widget Library
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { WIDGETS_BY_CATEGORY, CATEGORY_METADATA } from '@/lib/reports/widget-library';

export const dynamic = 'force-dynamic';

// GET - List widgets
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    const includeInactive = searchParams.get('includeInactive') === 'true';

    const where: Record<string, unknown> = {};
    if (category) where.category = category;
    if (!includeInactive) where.isActive = true;

    const widgets = await prisma.reportWidget.findMany({
      where,
      orderBy: [{ category: 'asc' }, { sortOrder: 'asc' }],
    });

    // Group by category
    const widgetsByCategory: Record<string, typeof widgets> = {};
    for (const widget of widgets) {
      if (!widgetsByCategory[widget.category]) {
        widgetsByCategory[widget.category] = [];
      }
      widgetsByCategory[widget.category].push(widget);
    }

    return NextResponse.json({
      widgets,
      widgetsByCategory,
      categoryMetadata: CATEGORY_METADATA,
      totalCount: widgets.length,
    });
  } catch (error) {
    console.error('Error fetching widgets:', error);
    // Fall back to static definitions
    return NextResponse.json({
      widgets: [],
      widgetsByCategory: WIDGETS_BY_CATEGORY,
      categoryMetadata: CATEGORY_METADATA,
      totalCount: 0,
    });
  }
}
