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

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const token = formData.get('token') as string;

    if (!file || !token) {
      return NextResponse.json(
        { error: 'File and token required' },
        { status: 400 }
      );
    }

    // 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 },
    });

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

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

    // Save uploaded file
    const buffer = Buffer.from(await file.arrayBuffer());
    const contractsDir = path.join(process.cwd(), 'public', 'contracts');
    await mkdir(contractsDir, { recursive: true });

    const filename = `contract-uploaded-${booking.bookingNumber}-${Date.now()}.pdf`;
    const filepath = path.join(contractsDir, filename);
    await writeFile(filepath, buffer);

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

    // Update booking
    await prisma.booking.update({
      where: { id: bookingId },
      data: {
        contractSigned: true,
        contractSignedAt: new Date(),
        contractSignedOnline: false,
        contractPdfUrl: contractUrl,
        contractSignedBy: booking.customerName,
      },
    });

    // TODO: Send email with confirmation to customer and admin

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