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

// POST /api/marketplace/purchase - Contractor purchases a contract
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { contractId, offeredPrice } = body;

    // Verify user is a contractor
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      include: { partnerProfile: true },
    });

    if (!user || user.role !== 'CONTRACTOR') {
      return NextResponse.json(
        { error: 'Only contractors can purchase contracts' },
        { status: 403 }
      );
    }

    // Check if contract is available
    const contract = await prisma.contract.findUnique({
      where: { id: contractId },
      include: {
        quote: true,
      },
    });

    if (!contract || !contract.isAvailable) {
      return NextResponse.json(
        { error: 'Contract not available' },
        { status: 404 }
      );
    }

    if (contract.partnerId) {
      return NextResponse.json(
        { error: 'Contract already assigned' },
        { status: 400 }
      );
    }

    // Calculate commission (20% platform fee)
    const purchasePrice = offeredPrice || contract.listPrice || contract.quote.total * 0.15;
    const commission = purchasePrice * 0.20;
    const contractorPayout = contract.quote.total - commission;

    // Create purchase record
    const purchase = await prisma.contractPurchase.create({
      data: {
        contractId,
        contractorId: user.id,
        purchasePrice,
        commission,
        contractorPayout,
        paymentStatus: 'PENDING',
        escrowStatus: 'PENDING',
      },
    });

    // Assign contract to contractor
    await prisma.contract.update({
      where: { id: contractId },
      data: {
        partnerId: user.partnerProfile?.id,
        isAvailable: false,
        status: 'IN_PROGRESS',
      },
    });

    // Create initial project milestones
    await createProjectMilestones(contractId, contract.quote.total);

    // Grant contractor access
    await prisma.contractPurchase.update({
      where: { id: purchase.id },
      data: {
        accessGrantedAt: new Date(),
      },
    });

    // Create notification
    await prisma.notification.create({
      data: {
        userId: user.id,
        title: 'Contract Purchased',
        message: `You have successfully purchased contract #${contract.contractNumber}`,
        type: 'SUCCESS',
      },
    });

    return NextResponse.json({
      success: true,
      purchase,
      message: 'Contract purchased successfully',
    });
  } catch (error) {
    console.error('Error purchasing contract:', error);
    return NextResponse.json(
      { error: 'Failed to purchase contract' },
      { status: 500 }
    );
  }
}

async function createProjectMilestones(contractId: string, totalAmount: number) {
  const milestones = [
    {
      milestone: 'DEPOSIT_RECEIVED' as const,
      title: 'Customer Deposit Received',
      photosRequired: false,
      paymentAmount: totalAmount * 0.30,
    },
    {
      milestone: 'WORK_SCHEDULED' as const,
      title: 'Work Scheduled',
      photosRequired: false,
      gpsRequired: false,
    },
    {
      milestone: 'WORK_STARTED' as const,
      title: 'Work Started',
      photosRequired: true,
      minPhotos: 3,
      gpsRequired: true,
    },
    {
      milestone: 'PROGRESS_50' as const,
      title: '50% Progress',
      photosRequired: true,
      minPhotos: 5,
      gpsRequired: true,
      paymentAmount: totalAmount * 0.30,
    },
    {
      milestone: 'WORK_COMPLETED' as const,
      title: 'Work Completed',
      photosRequired: true,
      minPhotos: 5,
      gpsRequired: true,
    },
    {
      milestone: 'CUSTOMER_APPROVED' as const,
      title: 'Customer Approval',
      photosRequired: false,
      paymentAmount: totalAmount * 0.40,
    },
  ];

  for (const milestone of milestones) {
    await prisma.projectMilestone.create({
      data: {
        contractId,
        ...milestone,
        status: 'PENDING' as const,
      },
    });
  }
}
