
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 timeRange = parseInt(searchParams.get('timeRange') || '6');
    const userId = searchParams.get('userId');

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

    // If user is a contractor, only show their own data
    if (session.user.role === 'CONTRACTOR') {
      where.userId = session.user.id;
    } else if (userId) {
      where.userId = userId;
    }

    // Fetch performance metrics
    const metrics = await prisma.contractorPerformance.findMany({
      where,
      include: {
        user: {
          select: {
            name: true,
            email: true,
            companyName: true,
          }
        },
        partner: {
          select: {
            companyName: true,
          }
        }
      },
      orderBy: {
        period: 'desc'
      },
      take: timeRange
    });

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

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

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

    // Only admins can create performance records manually
    if (session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await request.json();
    const {
      userId,
      partnerId,
      period,
      leadsAssigned,
      quotesSubmitted,
      contractsWon,
      revenue,
      averageRating,
      completionRate,
      customerSatisfaction
    } = body;

    // Validate required fields
    if (!userId || !partnerId || !period) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    // Create or update performance record
    const performance = await prisma.contractorPerformance.upsert({
      where: {
        userId_partnerId_period: {
          userId,
          partnerId,
          period
        }
      },
      update: {
        leadsAssigned: leadsAssigned || 0,
        quotesSubmitted: quotesSubmitted || 0,
        contractsWon: contractsWon || 0,
        revenue: revenue || 0,
        averageRating: averageRating || 0,
        completionRate: completionRate || 0,
        customerSatisfaction: customerSatisfaction || 0,
      },
      create: {
        userId,
        partnerId,
        period,
        leadsAssigned: leadsAssigned || 0,
        quotesSubmitted: quotesSubmitted || 0,
        contractsWon: contractsWon || 0,
        revenue: revenue || 0,
        averageRating: averageRating || 0,
        completionRate: completionRate || 0,
        customerSatisfaction: customerSatisfaction || 0,
      },
      include: {
        user: {
          select: {
            name: true,
            email: true,
          }
        },
        partner: {
          select: {
            companyName: true,
          }
        }
      }
    });

    return NextResponse.json(performance, { status: 201 });
  } catch (error) {
    console.error('Error creating performance record:', error);
    return NextResponse.json(
      { error: 'Failed to create performance record' },
      { status: 500 }
    );
  }
}
