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

// POST /api/financing/apply - Apply for project financing
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, downPayment, termMonths } = body;

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

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

    const totalAmount = contract.quote.total;
    const financedAmount = totalAmount - downPayment;
    const interestRate = 0.099; // 9.9% APR
    const monthlyInterestRate = interestRate / 12;
    
    // Calculate monthly payment using amortization formula
    const monthlyPayment =
      (financedAmount *
        monthlyInterestRate *
        Math.pow(1 + monthlyInterestRate, termMonths)) /
      (Math.pow(1 + monthlyInterestRate, termMonths) - 1);

    // Create financing application
    const financing = await prisma.projectFinancing.create({
      data: {
        contractId,
        customerId: session.user.id,
        totalAmount,
        downPayment,
        financedAmount,
        interestRate,
        termMonths,
        monthlyPayment,
        status: 'PENDING',
        paymentsRemaining: termMonths,
        nextPaymentDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
      },
    });

    return NextResponse.json({
      success: true,
      financing,
      monthlyPayment: monthlyPayment.toFixed(2),
    });
  } catch (error) {
    console.error('Error applying for financing:', error);
    return NextResponse.json(
      { error: 'Failed to apply for financing' },
      { status: 500 }
    );
  }
}
