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

export const dynamic = 'force-dynamic';

// GET /api/erp/crm - Get CRM dashboard stats
export async function GET() {
  try {
    const [customers, leads, opportunities, salesOrders] = await Promise.all([
      prisma.customer.count(),
      prisma.lead.count({ where: { status: { not: 'converted' } } }),
      prisma.opportunity.findMany({
        where: { stage: { in: ['qualification', 'proposal', 'negotiation', 'prospecting'] } },
        select: { expectedValue: true, probability: true }
      }),
      prisma.salesOrder.findMany({
        where: { status: { not: 'cancelled' } },
        select: { total: true, status: true }
      })
    ]);

    // Calculate pipeline value
    const pipelineValue = opportunities.reduce((sum, opp) => 
      sum + (opp.expectedValue || 0) * ((opp.probability || 50) / 100), 0);

    // Calculate revenue
    const completedOrders = salesOrders.filter(o => o.status === 'completed');
    const totalRevenue = completedOrders.reduce((sum, o) => sum + (o.total || 0), 0);
    const pendingRevenue = salesOrders
      .filter(o => o.status !== 'completed' && o.status !== 'cancelled')
      .reduce((sum, o) => sum + (o.total || 0), 0);

    return NextResponse.json({
      stats: {
        totalCustomers: customers,
        activeLeads: leads,
        pipelineValue,
        totalRevenue,
        pendingRevenue,
        openOpportunities: opportunities.length,
        openOrders: salesOrders.filter(o => o.status !== 'completed' && o.status !== 'cancelled').length
      }
    });
  } catch (error) {
    console.error('CRM stats error:', error);
    return NextResponse.json({ error: 'Failed to fetch CRM stats' }, { status: 500 });
  }
}
