import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { generateSignedContractPDF } from '@/lib/pdf-service';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { token, signatureData, name, email } = body;

    // Decode token to get booking ID
    const decoded = Buffer.from(token, 'base64url').toString();
    const bookingId = decoded.split('-')[0];

    const booking = await prisma.booking.findUnique({
      where: { id: bookingId },
      include: {
        location: true,
        photobox: true,
      },
    });

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

    if (booking.contractSigned) {
      return NextResponse.json(
        { error: 'Contract already signed' },
        { status: 400 }
      );
    }

    // Get client IP
    const ip = request.headers.get('x-forwarded-for') || 
               request.headers.get('x-real-ip') ||
               'unknown';

    const now = new Date();

    // Update booking with signature
    await prisma.booking.update({
      where: { id: bookingId },
      data: {
        contractSigned: true,
        contractSignedAt: now,
        contractSignedOnline: true,
        contractSignatureData: signatureData,
        contractSignedBy: name,
        contractSignedIp: ip,
      },
    });

    // Generate signed PDF
    const pdfBuffer = await generateSignedContractPDF(
      booking,
      booking.location,
      booking.photobox,
      signatureData,
      name,
      now,
      ip
    );

    // Save signed PDF
    const contractsDir = path.join(process.cwd(), 'public', 'contracts');
    await mkdir(contractsDir, { recursive: true });

    const filename = `contract-signed-${booking.bookingNumber}.pdf`;
    const filepath = path.join(contractsDir, filename);
    await writeFile(filepath, pdfBuffer);

    const contractUrl = `/contracts/${filename}`;

    await prisma.booking.update({
      where: { id: bookingId },
      data: {
        contractPdfUrl: contractUrl,
      },
    });

    // TODO: Send email with signed contract to customer and admin

    return NextResponse.json({
      success: true,
      message: 'Contract signed successfully',
    });
  } catch (error: any) {
    console.error('Contract signing error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to sign contract' },
      { status: 500 }
    );
  }
}
