import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { bookingAutomationService } from '@/lib/booking-automation';
import { prisma } from '@/lib/prisma';

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

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

    const { bookingId } = await request.json();

    if (!bookingId) {
      return NextResponse.json({ error: 'bookingId required' }, { status: 400 });
    }

    console.log(`🤖 Starte automatische Aktionen für Buchung: ${bookingId}`);

    const result = await bookingAutomationService.runPostBookingActions(bookingId);

    return NextResponse.json({
      success: true,
      emailSent: result.emailSent,
      calendarSynced: result.calendarSynced,
      lexofficeCreated: result.lexofficeCreated,
      contractGenerated: result.contractGenerated,
      errors: result.errors,
    });

  } catch (error: any) {
    console.error('❌ Automation Fehler:', error);
    return NextResponse.json(
      { error: error.message || 'Automation fehlgeschlagen' },
      { status: 500 }
    );
  }
}

// GET: Hole neueste Buchung und teste Automation
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

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

    // Hole neueste Buchung
    const latestBooking = await prisma.booking.findFirst({
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        bookingNumber: true,
        customerName: true,
        customerEmail: true,
        eventDate: true,
        calendarSynced: true,
      },
    });

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

    console.log(`🤖 Teste Automation für: ${latestBooking.bookingNumber}`);

    const result = await bookingAutomationService.runPostBookingActions(latestBooking.id);

    return NextResponse.json({
      success: true,
      booking: {
        id: latestBooking.id,
        bookingNumber: latestBooking.bookingNumber,
        customerName: latestBooking.customerName,
        customerEmail: latestBooking.customerEmail,
        eventDate: latestBooking.eventDate,
      },
      emailSent: result.emailSent,
      calendarSynced: result.calendarSynced,
      lexofficeCreated: result.lexofficeCreated,
      contractGenerated: result.contractGenerated,
      errors: result.errors,
    });

  } catch (error: any) {
    console.error('❌ Test Automation Fehler:', error);
    return NextResponse.json(
      { error: error.message || 'Test fehlgeschlagen' },
      { status: 500 }
    );
  }
}
