
/**
 * Phase 2: Role-Based Cockpit Dashboard API
 * Provides personalized dashboard data based on user role
 */

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

export async function GET(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const from = searchParams.get('from');
    const to = searchParams.get('to');
    const region = searchParams.get('region');

    // Calculate date range
    const startDate = from ? new Date(from) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const endDate = to ? new Date(to) : new Date();

    // Get basic dashboard stats
    const whereClause: any = {
      createdAt: { gte: startDate, lte: endDate }
    };
    
    if (region && region !== 'all') {
      whereClause.region = region;
    }

    const [activeProjects, pendingBadges, avgQuoteTimeData, dispatchCount] = await Promise.all([
      prisma.contract.count({
        where: {
          ...whereClause,
          status: { in: ['ACTIVE', 'IN_PROGRESS'] }
        }
      }),
      prisma.badgeRenewal.count({
        where: {
          renewalStatus: { in: ['PENDING', 'OVERDUE'] }
        }
      }),
      prisma.paymentLatency.aggregate({
        where: whereClause,
        _avg: { totalLatency: true }
      }),
      prisma.quoteRouting.count({
        where: {
          ...whereClause,
          routeStatus: 'ASSIGNED'
        }
      })
    ]);

    const totalDispatches = await prisma.quoteRouting.count({ where: whereClause });
    const dispatchEfficiency = totalDispatches > 0 ? Math.round((dispatchCount / totalDispatches) * 100) : 0;

    return NextResponse.json({
      activeProjects,
      pendingBadges,
      avgQuoteTime: Math.round(avgQuoteTimeData._avg.totalLatency || 0),
      dispatchEfficiency,
      onboardingPartners: 0 // TODO: Implement partner count
    });
  } catch (error) {
    console.error('Cockpit API Error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch dashboard data' },
      { status: 500 }
    );
  }
}

async function getAdminDashboard(userId: string, startDate: Date, region?: string | null) {
  const whereClause: any = {
    createdAt: { gte: startDate }
  };
  
  if (region) {
    whereClause.region = region;
  }

  const [
    totalLeads,
    totalQuotes,
    totalContracts,
    activeContractors,
    pendingRenewals,
    slaBreaches,
    avgQuoteLatency,
    revenueData
  ] = await Promise.all([
    prisma.lead.count({ where: whereClause }),
    prisma.quote.count({ where: whereClause }),
    prisma.contract.count({ where: whereClause }),
    prisma.partner.count({ where: { isVerified: true } }),
    prisma.badgeRenewal.count({
      where: {
        renewalStatus: { in: ['PENDING', 'OVERDUE'] }
      }
    }),
    prisma.sLATracking.count({
      where: {
        status: 'BREACHED',
        createdAt: { gte: startDate }
      }
    }),
    prisma.paymentLatency.aggregate({
      where: whereClause,
      _avg: { totalLatency: true }
    }),
    prisma.contract.aggregate({
      where: whereClause,
      _sum: { trustScore: true }
    })
  ]);

  return {
    metrics: {
      totalLeads,
      totalQuotes,
      totalContracts,
      activeContractors,
      pendingRenewals,
      slaBreaches,
      avgQuoteLatency: avgQuoteLatency._avg.totalLatency || 0,
      estimatedRevenue: revenueData._sum.trustScore || 0
    },
    role: 'ADMIN',
    timeRange: startDate
  };
}

async function getSalesDashboard(userId: string, startDate: Date, region?: string | null) {
  const whereClause: any = {
    createdAt: { gte: startDate },
    assignedToId: userId
  };

  if (region) {
    whereClause.region = region;
  }

  const [
    myLeads,
    myQuotes,
    convertedLeads,
    avgResponseTime
  ] = await Promise.all([
    prisma.lead.count({ where: whereClause }),
    prisma.quote.count({
      where: {
        userId,
        createdAt: { gte: startDate }
      }
    }),
    prisma.lead.count({
      where: {
        ...whereClause,
        status: 'CONVERTED'
      }
    }),
    // Average payment latency calculation
    Promise.resolve({ _avg: { totalLatency: 0 } })
  ]);

  return {
    metrics: {
      myLeads,
      myQuotes,
      convertedLeads,
      conversionRate: myLeads > 0 ? (convertedLeads / myLeads) * 100 : 0,
      avgResponseTime: avgResponseTime?._avg?.totalLatency || 0
    },
    role: 'SALES',
    timeRange: startDate
  };
}

async function getContractorDashboard(userId: string, startDate: Date, region?: string | null) {
  const partner = await prisma.partner.findUnique({
    where: { userId },
    select: { id: true }
  });

  if (!partner) {
    return {
      metrics: {},
      role: 'CONTRACTOR',
      timeRange: startDate
    };
  }

  const [
    activeJobs,
    completedJobs,
    totalRevenue,
    avgRating,
    pendingBadges
  ] = await Promise.all([
    prisma.contract.count({
      where: {
        partnerId: partner.id,
        status: { in: ['ACTIVE', 'IN_PROGRESS'] }
      }
    }),
    prisma.contract.count({
      where: {
        partnerId: partner.id,
        status: 'COMPLETED',
        actualCompletion: { gte: startDate }
      }
    }),
    prisma.contract.aggregate({
      where: {
        partnerId: partner.id,
        createdAt: { gte: startDate }
      },
      _sum: { trustScore: true }
    }),
    prisma.contractorReview.aggregate({
      where: {
        contractorId: userId,
        createdAt: { gte: startDate }
      },
      _avg: { overallRating: true }
    }),
    prisma.badgeRenewal.count({
      where: {
        contractorId: userId,
        renewalStatus: { in: ['PENDING', 'OVERDUE'] }
      }
    })
  ]);

  return {
    metrics: {
      activeJobs,
      completedJobs,
      totalRevenue: totalRevenue._sum.trustScore || 0,
      avgRating: avgRating._avg.overallRating || 0,
      pendingBadges
    },
    role: 'CONTRACTOR',
    timeRange: startDate
  };
}

async function getCustomerDashboard(userId: string, startDate: Date) {
  const [
    myQuotes,
    myContracts,
    activeProjects
  ] = await Promise.all([
    prisma.quote.count({
      where: {
        userId,
        createdAt: { gte: startDate }
      }
    }),
    prisma.contract.count({
      where: {
        userId,
        createdAt: { gte: startDate }
      }
    }),
    prisma.contract.count({
      where: {
        userId,
        status: { in: ['ACTIVE', 'IN_PROGRESS'] }
      }
    })
  ]);

  return {
    metrics: {
      myQuotes,
      myContracts,
      activeProjects
    },
    role: 'CUSTOMER',
    timeRange: startDate
  };
}
