
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { prisma } from '@/lib/db';

// GET /api/marketing/analytics - Get marketing analytics
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Get all campaigns
    const campaigns = await prisma.marketingCampaign.findMany();

    // Calculate overall analytics
    const totalBudget = campaigns.reduce((sum: number, c: any) => sum + c.budget, 0);
    const totalSpent = campaigns.reduce((sum: number, c: any) => sum + c.spent, 0);
    const totalRevenue = campaigns.reduce((sum: number, c: any) => sum + c.revenue, 0);
    const totalImpressions = campaigns.reduce((sum: number, c: any) => sum + c.impressions, 0);
    const totalClicks = campaigns.reduce((sum: number, c: any) => sum + c.clicks, 0);
    const totalLeads = campaigns.reduce((sum: number, c: any) => sum + c.leads, 0);
    const totalConversions = campaigns.reduce((sum: number, c: any) => sum + c.conversions, 0);

    const avgCPC = totalClicks > 0 ? totalSpent / totalClicks : 0;
    const avgCPL = totalLeads > 0 ? totalSpent / totalLeads : 0;
    const avgCPA = totalConversions > 0 ? totalSpent / totalConversions : 0;
    const overallROAS = totalSpent > 0 ? (totalRevenue / totalSpent) * 100 : 0;
    const overallROI = totalSpent > 0 ? ((totalRevenue - totalSpent) / totalSpent) * 100 : 0;

    // Channel breakdown
    const channelBreakdown = campaigns.reduce((acc: any, c: any) => {
      if (!acc[c.channel]) {
        acc[c.channel] = {
          count: 0,
          budget: 0,
          spent: 0,
          revenue: 0,
          leads: 0,
          conversions: 0,
        };
      }
      acc[c.channel].count += 1;
      acc[c.channel].budget += c.budget;
      acc[c.channel].spent += c.spent;
      acc[c.channel].revenue += c.revenue;
      acc[c.channel].leads += c.leads;
      acc[c.channel].conversions += c.conversions;
      return acc;
    }, {});

    // Top performing campaigns
    const topCampaigns = campaigns
      .map((c: any) => ({
        name: c.name,
        channel: c.channel,
        revenue: c.revenue,
        roi: c.spent > 0 ? ((c.revenue - c.spent) / c.spent) * 100 : 0,
        conversions: c.conversions,
      }))
      .sort((a: any, b: any) => b.roi - a.roi)
      .slice(0, 5);

    const analytics = {
      summary: {
        totalBudget,
        totalSpent,
        totalRevenue,
        totalImpressions,
        totalClicks,
        totalLeads,
        totalConversions,
        avgCPC: parseFloat(avgCPC.toFixed(2)),
        avgCPL: parseFloat(avgCPL.toFixed(2)),
        avgCPA: parseFloat(avgCPA.toFixed(2)),
        overallROAS: parseFloat(overallROAS.toFixed(2)),
        overallROI: parseFloat(overallROI.toFixed(2)),
      },
      channelBreakdown,
      topCampaigns,
      activeCampaigns: campaigns.filter((c: any) => c.isActive).length,
      totalCampaigns: campaigns.length,
    };

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