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

// GET /api/quote-rejections/analytics - Get rejection 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 rejections
    const rejections = await prisma.quoteRejection.findMany();

    // Calculate analytics
    const totalRejections = rejections.length;
    const recoveredCount = rejections.filter((r: any) => r.recovered).length;
    const recoveryRate = totalRejections > 0 ? (recoveredCount / totalRejections) * 100 : 0;

    // Rejection reasons breakdown
    const reasonsBreakdown = rejections.reduce((acc: any, r: any) => {
      acc[r.reason] = (acc[r.reason] || 0) + 1;
      return acc;
    }, {});

    // Price vs timeline issues
    const priceIssues = rejections.filter((r: any) => r.priceIssue).length;
    const timelineIssues = rejections.filter((r: any) => r.timelineIssue).length;

    // Top rejection reasons
    const topReasons = Object.entries(reasonsBreakdown)
      .sort(([, a]: any, [, b]: any) => b - a)
      .slice(0, 5)
      .map(([reason, count]) => ({ reason, count }));

    // Recent rejections
    const recentRejections = rejections
      .sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, 10);

    const analytics = {
      totalRejections,
      recoveredCount,
      recoveryRate: recoveryRate.toFixed(2),
      priceIssues,
      timelineIssues,
      reasonsBreakdown,
      topReasons,
      recentRejections,
    };

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