
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') || '12');

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

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

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

    // Generate CSV
    const headers = [
      'Period',
      'Contractor Name',
      'Company',
      'Email',
      'Leads Assigned',
      'Quotes Submitted',
      'Contracts Won',
      'Revenue',
      'Average Rating',
      'Completion Rate',
      'Customer Satisfaction'
    ];

    const rows = metrics.map((m: any) => [
      m.period,
      m.user.name || '',
      m.partner.companyName,
      m.user.email,
      m.leadsAssigned.toString(),
      m.quotesSubmitted.toString(),
      m.contractsWon.toString(),
      m.revenue.toString(),
      m.averageRating.toFixed(2),
      m.completionRate.toFixed(2),
      m.customerSatisfaction.toFixed(2)
    ]);

    const csv = [
      headers.join(','),
      ...rows.map((row: any[]) => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    return new NextResponse(csv, {
      headers: {
        'Content-Type': 'text/csv',
        'Content-Disposition': `attachment; filename="contractor-performance-${period}-${new Date().toISOString().split('T')[0]}.csv"`
      }
    });
  } catch (error) {
    console.error('Error exporting performance data:', error);
    return NextResponse.json(
      { error: 'Failed to export performance data' },
      { status: 500 }
    );
  }
}
