// API Routes for Report Email Delivery
import { NextRequest, NextResponse } from 'next/server';
import { sendExecutiveBriefEmail, testEmailDelivery, deliverScheduledReport, sendAlertEmail as sendAlertEmailBase } from '@/lib/reports/email-delivery';
import { generateReport } from '@/lib/reports/report-generator';
import { prisma } from '@/lib/db';
import type { AlertEmailData, ExecutiveBriefData } from '@/lib/reports/email-templates';
import type { ReportColumn } from '@/lib/reports/report-definitions';

// Wrapper for sendAlertEmail to match expected API signature
async function sendAlertEmail(recipients: string[], data: AlertEmailData) {
  const results = [];
  for (const recipient of recipients) {
    const result = await sendAlertEmailBase(
      recipient,
      data.alertType,
      data.title,
      data.message,
      {
        actionRequired: data.details,
        detailLink: data.actionUrl,
      }
    );
    results.push(result);
  }
  return {
    success: results.every(r => r.success),
    error: results.find(r => r.error)?.error,
  };
}

export const dynamic = 'force-dynamic';

// POST - Send report email
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;

    switch (action) {
      case 'send_report': {
        const { reportId, recipients, filters, subject, includeData } = body;

        if (!reportId || !recipients || recipients.length === 0) {
          return NextResponse.json(
            { error: 'Missing required fields: reportId, recipients' },
            { status: 400 }
          );
        }

        // Get report definition
        const report = await prisma.reportDefinition.findUnique({
          where: { id: reportId },
        });

        if (!report) {
          return NextResponse.json(
            { error: 'Report not found' },
            { status: 404 }
          );
        }

        // Parse columns from report definition
        const reportColumns = (report.columns as unknown as ReportColumn[]) || [];

        // Generate report data if requested
        let data: Record<string, unknown>[] = [];
        let columns: Array<{ key: string; label: string; type?: string }> = reportColumns.map((c) => ({
          key: c.key,
          label: c.label,
          type: c.format,
        }));

        if (includeData !== false) {
          const reportResult = await generateReport({
            reportId: report.id,
            filters: filters || {},
          });
          data = reportResult.rows;
        }

        // Send email
        const result = await deliverScheduledReport(
          recipients,
          report.name,
          report.description || undefined,
          data,
          columns,
          {
            summary: includeData ? calculateSummary(data, columns) : undefined,
          }
        );

        return NextResponse.json({
          success: result.success,
          error: result.error,
        });
      }

      case 'send_alert': {
        const { recipients, alertType, title, message, details, actionUrl, actionLabel } = body;

        if (!recipients || !title || !message) {
          return NextResponse.json(
            { error: 'Missing required fields: recipients, title, message' },
            { status: 400 }
          );
        }

        const alertData: AlertEmailData = {
          alertType: alertType || 'info',
          title,
          message,
          details,
          actionUrl,
          actionLabel,
        };

        const result = await sendAlertEmail(recipients, alertData);

        return NextResponse.json({
          success: result.success,
          error: result.error,
        });
      }

      case 'send_brief': {
        const { recipients, briefData } = body;

        if (!recipients || !briefData) {
          return NextResponse.json(
            { error: 'Missing required fields: recipients, briefData' },
            { status: 400 }
          );
        }

        const executiveBriefData: ExecutiveBriefData = {
          briefDate: new Date(briefData.briefDate || Date.now()),
          greeting: briefData.greeting,
          highlights: briefData.highlights || [],
          marketIntel: briefData.marketIntel,
          operationsHealth: briefData.operationsHealth,
          actionItems: briefData.actionItems,
          anomalies: briefData.anomalies,
        };

        const result = await sendExecutiveBriefEmail(recipients, executiveBriefData);

        return NextResponse.json({
          success: result.success,
          error: result.error,
        });
      }

      case 'test': {
        const { recipient } = body;

        if (!recipient) {
          return NextResponse.json(
            { error: 'Missing required field: recipient' },
            { status: 400 }
          );
        }

        const result = await testEmailDelivery(recipient);

        return NextResponse.json({
          success: result.success,
          error: result.error,
        });
      }

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: send_report, send_alert, send_brief, test' },
          { status: 400 }
        );
    }
  } catch (error) {
    console.error('Error in email API:', error);
    return NextResponse.json(
      { error: 'Failed to process email request' },
      { status: 500 }
    );
  }
}

// Helper to calculate summary from report data
function calculateSummary(
  data: Record<string, unknown>[],
  columns: Array<{ key: string; label: string; type?: string }>
): Record<string, unknown> {
  const summary: Record<string, unknown> = {
    total_records: data.length,
  };

  // Find numeric columns and calculate sums
  const numericColumns = columns.filter(
    (c) => c.type === 'currency' || c.type === 'number' || c.type === 'percentage'
  );

  for (const col of numericColumns) {
    const values = data
      .map((row) => Number(row[col.key]))
      .filter((v) => !isNaN(v));

    if (values.length > 0) {
      const sum = values.reduce((a, b) => a + b, 0);
      if (col.type === 'currency') {
        summary[`total_${col.key}`] = sum;
      } else if (col.type === 'percentage') {
        summary[`avg_${col.key}`] = sum / values.length;
      } else {
        summary[`total_${col.key}`] = sum;
      }
    }
  }

  return summary;
}
