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

// GET /api/admin/filters - Advanced admin filtering for dashboard
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    
    // Extract filter parameters
    const region = searchParams.get('region');
    const serviceType = searchParams.get('serviceType');
    const paymentStatus = searchParams.get('paymentStatus');
    const quoteStatus = searchParams.get('quoteStatus');
    const contractStatus = searchParams.get('contractStatus');
    const minRating = searchParams.get('minRating');
    const hasInsurance = searchParams.get('hasInsurance');
    const isReadyNow = searchParams.get('isReadyNow');
    const dateFrom = searchParams.get('dateFrom');
    const dateTo = searchParams.get('dateTo');

    // Build where clause for quotes
    const quoteWhere: any = {};
    if (region) quoteWhere.region = region;
    if (paymentStatus) quoteWhere.paymentStatus = paymentStatus;
    if (quoteStatus) quoteWhere.status = quoteStatus;
    if (serviceType) {
      quoteWhere.services = {
        has: serviceType,
      };
    }
    if (dateFrom || dateTo) {
      quoteWhere.createdAt = {};
      if (dateFrom) quoteWhere.createdAt.gte = new Date(dateFrom);
      if (dateTo) quoteWhere.createdAt.lte = new Date(dateTo);
    }

    // Fetch filtered quotes
    const quotes = await prisma.quote.findMany({
      where: quoteWhere,
      include: {
        lead: {
          select: {
            firstName: true,
            lastName: true,
            city: true,
            state: true,
            services: true,
          },
        },
        contracts: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 100,
    });

    // Build where clause for contracts
    const contractWhere: any = {};
    if (region) contractWhere.region = region;
    if (contractStatus) contractWhere.status = contractStatus;
    if (dateFrom || dateTo) {
      contractWhere.createdAt = {};
      if (dateFrom) contractWhere.createdAt.gte = new Date(dateFrom);
      if (dateTo) contractWhere.createdAt.lte = new Date(dateTo);
    }

    // Fetch filtered contracts
    const contracts = await prisma.contract.findMany({
      where: contractWhere,
      include: {
        quote: {
          include: {
            lead: true,
          },
        },
        partner: {
          include: {
            user: {
              select: {
                name: true,
                email: true,
              },
            },
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 100,
    });

    // Fetch contractors with filters
    const contractorWhere: any = {
      isVerified: true,
    };

    const contractors = await prisma.partner.findMany({
      where: contractorWhere,
      include: {
        user: {
          select: {
            name: true,
            email: true,
          },
        },
        performanceMetrics: {
          orderBy: {
            createdAt: 'desc',
          },
          take: 1,
        },
      },
    });

    // Filter contractors by rating if specified
    let filteredContractors = contractors;
    if (minRating) {
      const minRatingNum = parseFloat(minRating);
      filteredContractors = contractors.filter((c: any) => {
        const metrics = c.performanceMetrics[0];
        return metrics && metrics.averageRating >= minRatingNum;
      });
    }

    // Calculate statistics
    const stats = {
      totalQuotes: quotes.length,
      totalContracts: contracts.length,
      totalContractors: filteredContractors.length,
      quotesByStatus: quotes.reduce((acc: Record<string, number>, q: any) => {
        acc[q.status] = (acc[q.status] || 0) + 1;
        return acc;
      }, {}),
      contractsByStatus: contracts.reduce((acc: Record<string, number>, c: any) => {
        acc[c.status] = (acc[c.status] || 0) + 1;
        return acc;
      }, {}),
      paymentStatusBreakdown: quotes.reduce((acc: Record<string, number>, q: any) => {
        acc[q.paymentStatus] = (acc[q.paymentStatus] || 0) + 1;
        return acc;
      }, {}),
    };

    return NextResponse.json({
      quotes,
      contracts,
      contractors: filteredContractors,
      stats,
      filters: {
        region,
        serviceType,
        paymentStatus,
        quoteStatus,
        contractStatus,
        minRating,
        hasInsurance,
        isReadyNow,
        dateFrom,
        dateTo,
      },
    });
  } catch (error) {
    console.error('Error filtering admin data:', error);
    return NextResponse.json(
      { error: 'Failed to filter data' },
      { status: 500 }
    );
  }
}
