import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { aiService } from '@/lib/ai-service';

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const booking = await prisma.booking.findUnique({
      where: { id: params.id },
      include: {
        emails: {
          orderBy: { receivedAt: 'desc' },
          take: 1,
        },
      },
    });

    if (!booking) {
      return NextResponse.json({ error: 'Buchung nicht gefunden' }, { status: 404 });
    }

    if (!booking.emails || booking.emails.length === 0) {
      return NextResponse.json({ error: 'Keine E-Mail gefunden' }, { status: 400 });
    }

    const email = booking.emails[0];
    
    const result = await aiService.parseBookingEmail(
      email.htmlBody || email.textBody || '',
      email.subject
    );

    await prisma.booking.update({
      where: { id: params.id },
      data: {
        aiParsed: true,
        aiResponseDraft: result.responseDraft,
        aiProcessedAt: new Date(),
        customerName: result.parsed.customerName || booking.customerName,
        customerEmail: result.parsed.customerEmail || booking.customerEmail,
        customerPhone: result.parsed.customerPhone || booking.customerPhone,
        customerAddress: result.parsed.customerAddress,
        customerCity: result.parsed.customerCity,
        customerZip: result.parsed.customerZip,
        companyName: result.parsed.companyName,
        invoiceType: result.parsed.invoiceType,
        eventAddress: result.parsed.eventAddress || booking.eventAddress,
        eventCity: result.parsed.eventCity || booking.eventCity,
        eventZip: result.parsed.eventZip || booking.eventZip,
        eventLocation: result.parsed.eventLocation,
        eventDate: new Date(result.parsed.eventDate || booking.eventDate),
        setupTimeStart: new Date(result.parsed.setupTimeStart || booking.setupTimeStart),
      },
    });

    return NextResponse.json({
      success: true,
      parsed: result.parsed,
      responseDraft: result.responseDraft,
      confidence: result.confidence,
    });
  } catch (error) {
    console.error('AI Analysis error:', error);
    return NextResponse.json(
      { error: 'KI-Analyse fehlgeschlagen' },
      { status: 500 }
    );
  }
}
