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

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Get current date for filtering
    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);

    // Base query conditions based on user role
    const userRole = session.user.role;
    let whereCondition: any = {};

    if (userRole === 'SALES') {
      whereCondition = { assignedToId: session.user.id };
    } else if (userRole === 'CONTRACTOR') {
      const partner = await prisma.partner.findUnique({
        where: { userId: session.user.id },
      });
      if (partner) {
        whereCondition = { partnerId: partner.id };
      }
    }

    // Fetch leads statistics
    const [totalLeads, newLeads, qualifiedLeads, convertedLeads] = await Promise.all([
      prisma.lead.count({ where: whereCondition }),
      prisma.lead.count({ 
        where: { 
          ...whereCondition, 
          status: 'NEW',
          createdAt: { gte: startOfMonth, lte: endOfMonth }
        } 
      }),
      prisma.lead.count({ 
        where: { 
          ...whereCondition, 
          status: 'QUALIFIED' 
        } 
      }),
      prisma.lead.count({ 
        where: { 
          ...whereCondition, 
          status: 'CONVERTED' 
        } 
      }),
    ]);

    // Fetch quotes statistics
    const [totalQuotes, sentQuotes, acceptedQuotes, pendingQuotes] = await Promise.all([
      prisma.quote.count({ 
        where: userRole === 'CONTRACTOR' && whereCondition.partnerId 
          ? { partnerId: whereCondition.partnerId } 
          : {} 
      }),
      prisma.quote.count({ 
        where: { 
          status: 'SENT',
          ...(userRole === 'CONTRACTOR' && whereCondition.partnerId 
            ? { partnerId: whereCondition.partnerId } 
            : {})
        } 
      }),
      prisma.quote.count({ 
        where: { 
          status: 'ACCEPTED',
          ...(userRole === 'CONTRACTOR' && whereCondition.partnerId 
            ? { partnerId: whereCondition.partnerId } 
            : {})
        } 
      }),
      prisma.quote.count({ 
        where: { 
          status: { in: ['SENT', 'VIEWED'] },
          ...(userRole === 'CONTRACTOR' && whereCondition.partnerId 
            ? { partnerId: whereCondition.partnerId } 
            : {})
        } 
      }),
    ]);

    // Fetch contracts statistics
    const contracts = await prisma.contract.findMany({
      where: userRole === 'CONTRACTOR' && whereCondition.partnerId 
        ? { partnerId: whereCondition.partnerId } 
        : {},
      include: { quote: true },
    });

    const totalContracts = contracts.length;
    const activeContracts = contracts.filter((c: any) => c.status === 'ACTIVE' || c.status === 'IN_PROGRESS').length;
    const completedContracts = contracts.filter((c: any) => c.status === 'COMPLETED').length;
    
    // Calculate revenue from contracts created this month
    const monthlyRevenue = contracts
      .filter((c: any) => c.createdAt >= startOfMonth && c.createdAt <= endOfMonth)
      .reduce((sum: number, contract: any) => sum + (contract.quote?.total || 0), 0);

    // Fetch partners statistics (for admin/sales users)
    let partnersStats = { total: 0, active: 0, topPerformer: 'N/A' };
    if (userRole === 'ADMIN' || userRole === 'SALES') {
      const totalPartners = await prisma.partner.count();
      const activePartners = await prisma.partner.count({ 
        where: { isVerified: true, user: { isActive: true } } 
      });
      
      // Get top performing partner
      const topPartner = await prisma.partner.findFirst({
        include: {
          contracts: {
            where: {
              createdAt: { gte: startOfMonth, lte: endOfMonth }
            }
          }
        },
        orderBy: {
          contracts: {
            _count: 'desc'
          }
        }
      });

      partnersStats = {
        total: totalPartners,
        active: activePartners,
        topPerformer: topPartner?.companyName || 'N/A',
      };
    }

    const stats = {
      leads: {
        total: totalLeads,
        new: newLeads,
        qualified: qualifiedLeads,
        converted: convertedLeads,
      },
      quotes: {
        total: totalQuotes,
        sent: sentQuotes,
        accepted: acceptedQuotes,
        pending: pendingQuotes,
      },
      contracts: {
        total: totalContracts,
        active: activeContracts,
        completed: completedContracts,
        revenue: monthlyRevenue,
      },
      partners: partnersStats,
    };

    return NextResponse.json(stats);

  } catch (error) {
    console.error('Dashboard stats error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
