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

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

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
    });

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

    // Get all referral codes and their performance
    const referralCodes = await prisma.referralCode.findMany({
      where: { referrerId: user.id },
      include: {
        referrals: true,
      },
    });

    // Calculate analytics
    const analytics = {
      totalCodes: referralCodes.length,
      activeCodes: referralCodes.filter((c: any) => c.isActive).length,
      totalReferrals: referralCodes.reduce((sum: number, c: any) => sum + c.timesUsed, 0),
      totalConversions: referralCodes.reduce((sum: number, c: any) => sum + c.conversions, 0),
      totalRevenue: referralCodes.reduce((sum: number, c: any) => sum + c.totalRevenue, 0),
      conversionRate:
        referralCodes.reduce((sum: number, c: any) => sum + c.timesUsed, 0) > 0
          ? (referralCodes.reduce((sum: number, c: any) => sum + c.conversions, 0) /
              referralCodes.reduce((sum: number, c: any) => sum + c.timesUsed, 0)) *
            100
          : 0,
      topPerformingCodes: referralCodes
        .sort((a: any, b: any) => b.conversions - a.conversions)
        .slice(0, 5)
        .map((c: any) => ({
          code: c.code,
          conversions: c.conversions,
          revenue: c.totalRevenue,
        })),
    };

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