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

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 booking = await prisma.booking.findUnique({
      where: { id },
      include: {
        location: true,
        photobox: true,
      },
    });

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

    // Generate PDF
    const pdfBuffer = await generateContractPDF(booking, booking.location, booking.photobox);

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

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

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

    // Update booking
    await prisma.booking.update({
      where: { id },
      data: {
        contractGenerated: true,
        contractGeneratedAt: new Date(),
        contractPdfUrl: contractUrl,
      },
    });

    return NextResponse.json({
      success: true,
      contractUrl,
      filename,
    });
  } catch (error: any) {
    console.error('Contract generation error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to generate contract' },
      { status: 500 }
    );
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;

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

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

    // Generate PDF in memory for download
    const pdfBuffer = await generateSignedContractPDF(
      booking,
      booking.location,
      booking.photobox,
      booking.contractSignatureData || '',
      booking.contractSignedBy || '',
      booking.contractSignedAt || new Date(),
      booking.contractSignedIp || ''
    );

    return new NextResponse(new Uint8Array(pdfBuffer), {
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="Vertrag-${booking.bookingNumber}.pdf"`,
      },
    });
  } catch (error: any) {
    console.error('Contract download error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to download contract' },
      { status: 500 }
    );
  }
}
