import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { sendContractEmail } from '@/lib/email-service';

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

    if (!booking.contractGenerated || !booking.contractPdfUrl) {
      return NextResponse.json(
        { error: 'Contract not generated yet. Please generate contract first.' },
        { status: 400 }
      );
    }

    try {
      await sendContractEmail(booking, booking.contractPdfUrl);
      
      await prisma.booking.update({
        where: { id },
        data: {
          contractSentAt: new Date(),
        },
      });

      return NextResponse.json({
        success: true,
        message: `Contract sent to ${booking.customerEmail}`,
      });
    } catch (emailError: any) {
      console.error('Email send error:', emailError);
      
      if (emailError.message?.includes('SMTP not configured')) {
        return NextResponse.json({
          success: false,
          error: 'E-Mail-Service nicht konfiguriert. Bitte SMTP-Einstellungen in .env hinzufügen.',
        }, { status: 503 });
      }
      
      return NextResponse.json({
        success: false,
        error: emailError.message || 'Failed to send email',
      }, { status: 500 });
    }
  } catch (error: any) {
    console.error('Contract send error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to send contract' },
      { status: 500 }
    );
  }
}
