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

// GET /api/milestones/[contractId] - Get project milestones
export async function GET(
  request: NextRequest,
  { params }: { params: { contractId: string } }
) {
  try {
    const { contractId } = params;

    const milestones = await prisma.projectMilestone.findMany({
      where: { contractId },
      orderBy: { createdAt: 'asc' },
    });

    // Get uploaded photos for each milestone
    const milestonesWithPhotos = await Promise.all(
      milestones.map(async (milestone: any) => {
        const photos = await prisma.fileUpload.findMany({
          where: { milestoneId: milestone.id },
        });
        return {
          ...milestone,
          photos,
        };
      })
    );

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

// PATCH /api/milestones/[contractId] - Update milestone status
export async function PATCH(
  request: NextRequest,
  { params }: { params: { contractId: string } }
) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { milestoneId, status, notes } = body;

    const milestone = await prisma.projectMilestone.update({
      where: { id: milestoneId },
      data: {
        status,
        notes,
        actualDate: status === 'COMPLETED' ? new Date() : undefined,
        completedAt: status === 'COMPLETED' ? new Date() : undefined,
      },
    });

    // If milestone completed and payment required, release payment
    if (status === 'COMPLETED' && milestone.paymentAmount && !milestone.paymentReleased) {
      await releasePayment(milestone.contractId, milestone.paymentAmount);
      
      await prisma.projectMilestone.update({
        where: { id: milestoneId },
        data: {
          paymentReleased: true,
          paymentDate: new Date(),
        },
      });
    }

    return NextResponse.json({
      success: true,
      milestone,
    });
  } catch (error) {
    console.error('Error updating milestone:', error);
    return NextResponse.json(
      { error: 'Failed to update milestone' },
      { status: 500 }
    );
  }
}

async function releasePayment(contractId: string, amount: number) {
  // Create escrow transaction to release funds
  const contract = await prisma.contract.findUnique({
    where: { id: contractId },
    include: {
      quote: {
        include: { lead: true },
      },
    },
  });

  if (!contract) return;

  const purchase = await prisma.contractPurchase.findUnique({
    where: { contractId },
  });

  if (!purchase) return;

  await prisma.escrowTransaction.create({
    data: {
      contractId,
      purchaseId: purchase.id,
      amount,
      currency: 'ZAR',
      status: 'RELEASED',
      payerId: contract.userId,
      payeeId: purchase.contractorId,
      platformFee: amount * 0.20,
      releasedAt: new Date(),
    },
  });
}
