// API Routes for Report Definitions
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { initializeReportDefinitions, MODULE_METADATA } from '@/lib/reports/report-definitions';
import { initializeWidgetLibrary } from '@/lib/reports/widget-library';

export const dynamic = 'force-dynamic';

// GET - List all reports, optionally filtered by module
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const module = searchParams.get('module');
    const category = searchParams.get('category');
    const includeInactive = searchParams.get('includeInactive') === 'true';

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

    const reports = await prisma.reportDefinition.findMany({
      where,
      orderBy: [{ module: 'asc' }, { sortOrder: 'asc' }],
      select: {
        id: true,
        key: true,
        name: true,
        description: true,
        module: true,
        category: true,
        reportType: true,
        permissions: true,
        isActive: true,
        isSystem: true,
        sortOrder: true,
        _count: {
          select: {
            schedules: { where: { isEnabled: true } },
            subscriptions: { where: { isActive: true } },
          },
        },
      },
    });

    // Group by module
    const reportsByModule: Record<string, typeof reports> = {};
    for (const report of reports) {
      if (!reportsByModule[report.module]) {
        reportsByModule[report.module] = [];
      }
      reportsByModule[report.module].push(report);
    }

    return NextResponse.json({
      reports,
      reportsByModule,
      moduleMetadata: MODULE_METADATA,
      totalCount: reports.length,
    });
  } catch (error) {
    console.error('Error fetching reports:', error);
    return NextResponse.json(
      { error: 'Failed to fetch reports' },
      { status: 500 }
    );
  }
}

// POST - Initialize/seed all report definitions and widgets
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;

    if (action === 'initialize') {
      // Initialize all report definitions
      await initializeReportDefinitions(prisma);
      await initializeWidgetLibrary(prisma);

      const reportCount = await prisma.reportDefinition.count();
      const widgetCount = await prisma.reportWidget.count();

      return NextResponse.json({
        success: true,
        message: 'Report definitions and widgets initialized',
        reportCount,
        widgetCount,
      });
    }

    return NextResponse.json(
      { error: 'Invalid action' },
      { status: 400 }
    );
  } catch (error) {
    console.error('Error initializing reports:', error);
    return NextResponse.json(
      { error: 'Failed to initialize reports' },
      { status: 500 }
    );
  }
}
