// API Routes for Generated Report History
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getGeneratedReports } from '@/lib/reports/report-scheduler';

export const dynamic = 'force-dynamic';

// GET - Get generated report history
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const reportId = searchParams.get('reportId') || undefined;
    const userId = searchParams.get('userId') || undefined;
    const scheduleId = searchParams.get('scheduleId') || undefined;
    const triggerType = searchParams.get('triggerType') || undefined;
    const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit')!) : 50;
    const offset = searchParams.get('offset') ? parseInt(searchParams.get('offset')!) : 0;

    const reports = await getGeneratedReports({
      reportId,
      userId,
      scheduleId,
      triggerType,
      limit,
      offset,
    });

    const total = await prisma.generatedReport.count({
      where: {
        ...(reportId && { reportId }),
        ...(userId && { generatedFor: userId }),
        ...(scheduleId && { scheduleId }),
        ...(triggerType && { triggerType }),
      },
    });

    return NextResponse.json({
      reports,
      pagination: {
        limit,
        offset,
        total,
        hasMore: offset + reports.length < total,
      },
    });
  } catch (error) {
    console.error('Error fetching report history:', error);
    return NextResponse.json(
      { error: 'Failed to fetch report history' },
      { status: 500 }
    );
  }
}

// DELETE - Delete old generated reports
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const reportIdToDelete = searchParams.get('id');
    const olderThanDays = searchParams.get('olderThanDays');

    if (reportIdToDelete) {
      await prisma.generatedReport.delete({
        where: { id: reportIdToDelete },
      });
      return NextResponse.json({ success: true, deletedCount: 1 });
    }

    if (olderThanDays) {
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - parseInt(olderThanDays));

      const result = await prisma.generatedReport.deleteMany({
        where: {
          createdAt: { lt: cutoffDate },
        },
      });

      return NextResponse.json({
        success: true,
        deletedCount: result.count,
      });
    }

    return NextResponse.json(
      { error: 'Specify either id or olderThanDays' },
      { status: 400 }
    );
  } catch (error) {
    console.error('Error deleting reports:', error);
    return NextResponse.json(
      { error: 'Failed to delete reports' },
      { status: 500 }
    );
  }
}
