
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/db';
import { pdfService } from '@/lib/pdf-service';
import { uploadFile } from '@/lib/s3';

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { quoteId } = body;

    if (!quoteId) {
      return NextResponse.json({ error: 'Quote ID is required' }, { status: 400 });
    }

    // Fetch quote details
    const quote = await prisma.quote.findUnique({
      where: { id: quoteId },
      include: {
        user: true,
        lead: true,
        partner: true
      }
    });

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

    // Check if contract already exists for this quote
    const existingContract = await prisma.contract.findFirst({
      where: { quoteId: quoteId }
    });

    if (existingContract) {
      return NextResponse.json({ 
        error: 'Contract already exists for this quote',
        contractId: existingContract.id
      }, { status: 400 });
    }

    // Generate contract number
    const contractCount = await prisma.contract.count();
    const contractNumber = `CNT-${new Date().getFullYear()}-${String(contractCount + 1).padStart(5, '0')}`;

    // Prepare quote data for PDF generation
    const quoteData = {
      id: quote.id,
      quoteNumber: quote.quoteNumber,
      clientName: quote.user.name || '',
      clientEmail: quote.user.email,
      clientCompany: quote.user.companyName || undefined,
      clientPhone: quote.user.phone || undefined,
      clientAddress: quote.user.address || undefined,
      serviceName: quote.services.join(', '),
      serviceDescription: quote.notes || undefined,
      lineItems: quote.lineItems,
      total: quote.total,
      subtotal: quote.subtotal,
      taxes: quote.taxes,
      discounts: quote.discounts,
      paymentTerms: quote.termsConditions || undefined,
      validUntil: quote.validUntil.toISOString(),
    };

    // Generate PDF contract
    const contract = await pdfService.generateContract(quoteData, contractNumber);

    // Upload PDF to S3
    const pdfBuffer = Buffer.from(contract.pdfBytes);
    const pdfStoragePath = await uploadFile(pdfBuffer, `contract-${contractNumber}.pdf`);

    // Save contract to database
    const savedContract = await prisma.contract.create({
      data: {
        contractNumber: contractNumber,
        quoteId: quote.id,
        userId: quote.userId,
        partnerId: quote.partnerId,
        templateVersion: '1.0',
        contractData: {
          quoteData,
          generatedBy: session.user.id,
          generatedAt: new Date().toISOString()
        },
        trustScore: 0.0,
        pdfStoragePath: pdfStoragePath,
        status: 'DRAFT'
      },
      include: {
        quote: true,
        user: true,
        signatures: true
      }
    });

    // Return contract data with PDF as base64
    const pdfBase64 = Buffer.from(contract.pdfBytes).toString('base64');
    
    return NextResponse.json({
      success: true,
      contract: {
        id: savedContract.id,
        contractNumber: savedContract.contractNumber,
        contractId: contract.contractId,
        pdfData: pdfBase64,
        pdfStoragePath: pdfStoragePath,
        status: savedContract.status,
        metadata: contract.metadata
      }
    });
  } catch (error) {
    console.error('Error generating contract:', error);
    return NextResponse.json(
      { error: 'Failed to generate contract' },
      { status: 500 }
    );
  }
}
