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

// Note: Google Vision API can be added later for automatic signature detection
// For now, we trust admin verification

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { id } = params;
    const formData = await request.formData();
    const file = formData.get('file') as File;

    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 });
    }

    const booking = await prisma.booking.findUnique({
      where: { id },
    });

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

    // 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 },
      data: {
        contractSigned: true,
        contractSignedAt: new Date(),
        contractSignedOnline: false,
        contractPdfUrl: contractUrl,
        contractSignedBy: booking.customerName,
        contractUploadedBy: session.user.id,
      },
    });

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