// API Routes for Report Schedules
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import {
  createReportSchedule,
  updateReportSchedule,
  deleteReportSchedule,
  getDueSchedules,
  executeScheduledReport,
} from '@/lib/reports/report-scheduler';
import type { ScheduleConfig, DeliveryConfig } from '@/lib/reports/report-scheduler';

export const dynamic = 'force-dynamic';

// GET - List schedules
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const reportId = searchParams.get('reportId');
    const action = searchParams.get('action');

    if (action === 'due') {
      const dueSchedules = await getDueSchedules();
      return NextResponse.json({ schedules: dueSchedules });
    }

    const where: Record<string, unknown> = {};
    if (reportId) where.reportId = reportId;

    const schedules = await prisma.reportSchedule.findMany({
      where,
      include: {
        report: { select: { name: true, module: true } },
      },
      orderBy: { createdAt: 'desc' },
    });

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

// POST - Create schedule or execute
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, scheduleId, reportId, name, schedule, delivery, filters, createdById } = body;

    if (action === 'execute' && scheduleId) {
      const result = await executeScheduledReport(scheduleId);
      return NextResponse.json({
        success: true,
        generatedReportId: result.generatedReportId,
      });
    }

    if (action === 'create') {
      if (!reportId || !name || !schedule || !delivery) {
        return NextResponse.json(
          { error: 'Missing required fields: reportId, name, schedule, delivery' },
          { status: 400 }
        );
      }

      const result = await createReportSchedule(
        reportId,
        name,
        schedule as ScheduleConfig,
        delivery as DeliveryConfig,
        filters || {},
        createdById
      );

      return NextResponse.json({
        success: true,
        scheduleId: result.id,
        nextRunAt: result.nextRunAt,
      });
    }

    return NextResponse.json(
      { error: 'Invalid action' },
      { status: 400 }
    );
  } catch (error) {
    console.error('Error with schedule:', error);
    return NextResponse.json(
      { error: 'Failed to process schedule request' },
      { status: 500 }
    );
  }
}

// PATCH - Update schedule
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { scheduleId, ...updates } = body;

    if (!scheduleId) {
      return NextResponse.json(
        { error: 'Schedule ID required' },
        { status: 400 }
      );
    }

    const result = await updateReportSchedule(scheduleId, updates);

    return NextResponse.json({
      success: true,
      scheduleId: result.id,
      nextRunAt: result.nextRunAt,
    });
  } catch (error) {
    console.error('Error updating schedule:', error);
    return NextResponse.json(
      { error: 'Failed to update schedule' },
      { status: 500 }
    );
  }
}

// DELETE - Delete schedule
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const scheduleId = searchParams.get('scheduleId');

    if (!scheduleId) {
      return NextResponse.json(
        { error: 'Schedule ID required' },
        { status: 400 }
      );
    }

    await deleteReportSchedule(scheduleId);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting schedule:', error);
    return NextResponse.json(
      { error: 'Failed to delete schedule' },
      { status: 500 }
    );
  }
}
