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

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

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

    const { searchParams } = new URL(request.url);
    const period = searchParams.get('period') || 'monthly';
    const userId = searchParams.get('userId');

    // Build where clause
    const where: any = {
      period: {
        contains: period
      }
    };

    if (session.user.role === 'CONTRACTOR') {
      where.userId = session.user.id;
    } else if (userId) {
      where.userId = userId;
    }

    // Get current period stats
    const currentStats = await prisma.contractorPerformance.aggregate({
      where,
      _sum: {
        revenue: true,
        contractsWon: true,
      },
      _avg: {
        averageRating: true,
        completionRate: true,
      }
    });

    // Get previous period for comparison
    const previousPeriodDate = getPreviousPeriod(getCurrentPeriod(period));
    const previousWhere = {
      ...where,
      period: previousPeriodDate
    };

    const previousStats = await prisma.contractorPerformance.aggregate({
      where: previousWhere,
      _sum: {
        revenue: true,
        contractsWon: true,
      },
      _avg: {
        averageRating: true,
        completionRate: true,
      }
    });

    // Calculate changes
    const calculateChange = (current: number, previous: number) => {
      if (!previous || previous === 0) return 0;
      return ((current - previous) / previous) * 100;
    };

    const stats = {
      totalRevenue: currentStats._sum.revenue || 0,
      totalContracts: currentStats._sum.contractsWon || 0,
      averageRating: currentStats._avg.averageRating || 0,
      completionRate: currentStats._avg.completionRate || 0,
      revenueChange: calculateChange(
        currentStats._sum.revenue || 0,
        previousStats._sum.revenue || 0
      ),
      contractsChange: calculateChange(
        currentStats._sum.contractsWon || 0,
        previousStats._sum.contractsWon || 0
      ),
      ratingChange: (currentStats._avg.averageRating || 0) - (previousStats._avg.averageRating || 0),
      completionChange: (currentStats._avg.completionRate || 0) - (previousStats._avg.completionRate || 0),
    };

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

function getCurrentPeriod(periodType: string): string {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  
  if (periodType === 'monthly') {
    return `${year}-${month.toString().padStart(2, '0')}`;
  } else if (periodType === 'quarterly') {
    const quarter = Math.ceil(month / 3);
    return `${year}-Q${quarter}`;
  } else {
    return `${year}`;
  }
}

function getPreviousPeriod(currentPeriod: string): string {
  // Handle monthly periods (YYYY-MM)
  const monthMatch = currentPeriod.match(/(\d{4})-(\d{2})/);
  if (monthMatch) {
    let year = parseInt(monthMatch[1]);
    let month = parseInt(monthMatch[2]);
    
    month--;
    if (month === 0) {
      month = 12;
      year--;
    }
    
    return `${year}-${month.toString().padStart(2, '0')}`;
  }
  
  // Handle quarterly periods (YYYY-QN)
  const quarterMatch = currentPeriod.match(/(\d{4})-Q(\d)/);
  if (quarterMatch) {
    let year = parseInt(quarterMatch[1]);
    let quarter = parseInt(quarterMatch[2]);
    
    quarter--;
    if (quarter === 0) {
      quarter = 4;
      year--;
    }
    
    return `${year}-Q${quarter}`;
  }
  
  // Handle yearly periods (YYYY)
  const yearMatch = currentPeriod.match(/^(\d{4})$/);
  if (yearMatch) {
    const year = parseInt(yearMatch[1]) - 1;
    return `${year}`;
  }
  
  return currentPeriod;
}
