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

// GET /api/marketplace/contracts - Browse available contracts for purchase
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const region = searchParams.get('region');
    const serviceType = searchParams.get('serviceType');
    const maxPrice = searchParams.get('maxPrice');
    const minPrice = searchParams.get('minPrice');

    // Build filter
    const where: any = {
      isAvailable: true,
      status: 'ACTIVE',
      partnerId: null, // Not yet assigned to a contractor
    };

    if (region) where.region = region;
    if (maxPrice) where.listPrice = { ...where.listPrice, lte: parseFloat(maxPrice) };
    if (minPrice) where.listPrice = { ...where.listPrice, gte: parseFloat(minPrice) };

    const contracts = await prisma.contract.findMany({
      where,
      include: {
        quote: {
          include: {
            lead: {
              select: {
                address: true,
                city: true,
                state: true,
                latitude: true,
                longitude: true,
                services: true,
              },
            },
          },
        },
        user: {
          select: {
            name: true,
            email: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 50,
    });

    // Calculate distance from contractor if they have a profile
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      include: { partnerProfile: true },
    });

    const contractsWithDistance = contracts.map((contract: any) => {
      let distance = null;
      if (user?.partnerProfile && contract.quote.lead.latitude && contract.quote.lead.longitude) {
        // Simple distance calculation - in production use proper geo library
        distance = calculateDistance(
          user.partnerProfile.businessAddress,
          contract.quote.lead.latitude,
          contract.quote.lead.longitude
        );
      }

      return {
        ...contract,
        distance,
      };
    });

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

function calculateDistance(address: string, lat: number, lng: number): number {
  // Placeholder - in production, use geocoding + haversine formula
  return Math.random() * 50; // km
}
