// API Routes for Report Subscriptions
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import {
  subscribeToReport,
  unsubscribeFromReport,
  getUserSubscriptions,
  getDueSubscriptions,
  executeSubscriptionDelivery,
} from '@/lib/reports/report-scheduler';

export const dynamic = 'force-dynamic';

// GET - Get user's subscriptions
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const action = searchParams.get('action');

    if (action === 'due') {
      const dueSubscriptions = await getDueSubscriptions();
      return NextResponse.json({ subscriptions: dueSubscriptions });
    }

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

    const subscriptions = await getUserSubscriptions(userId);

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

// POST - Subscribe to report or execute delivery
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      action,
      subscriptionId,
      userId,
      reportId,
      frequency,
      dayOfWeek,
      dayOfMonth,
      timeOfDay,
      timezone,
      format,
      deliveryChannel,
      filters,
    } = body;

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

    if (action === 'subscribe') {
      if (!userId || !reportId || !frequency) {
        return NextResponse.json(
          { error: 'Missing required fields: userId, reportId, frequency' },
          { status: 400 }
        );
      }

      const result = await subscribeToReport(userId, reportId, frequency, {
        dayOfWeek,
        dayOfMonth,
        timeOfDay,
        timezone,
        format,
        deliveryChannel,
        filters,
      });

      return NextResponse.json({
        success: true,
        subscriptionId: result.id,
        nextDeliveryAt: result.nextDeliveryAt,
      });
    }

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

// DELETE - Unsubscribe from report
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const reportId = searchParams.get('reportId');

    if (!userId || !reportId) {
      return NextResponse.json(
        { error: 'User ID and Report ID required' },
        { status: 400 }
      );
    }

    await unsubscribeFromReport(userId, reportId);

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