import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { nextcloudCalendar } from '@/lib/nextcloud-calendar';
import { prisma } from '@/lib/prisma';

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

    const { action, bookingId } = await req.json();

    if (action === 'test-connection') {
      try {
        const calendars = await nextcloudCalendar.getCalendars();
        return NextResponse.json({ 
          success: true, 
          calendars: calendars.map((cal: any) => ({
            displayName: cal.displayName,
            url: cal.url,
            description: cal.description,
          }))
        });
      } catch (error: any) {
        return NextResponse.json({ 
          success: false, 
          error: error.message 
        }, { status: 500 });
      }
    }

    if (action === 'sync-booking' && bookingId) {
      const booking = await prisma.booking.findUnique({
        where: { id: bookingId },
        include: {
          location: true,
          photobox: true,
        },
      });

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

      try {
        await nextcloudCalendar.syncBookingToCalendar(booking);
        return NextResponse.json({ success: true, message: 'Booking synced to calendar' });
      } catch (error: any) {
        return NextResponse.json({ 
          success: false, 
          error: error.message 
        }, { status: 500 });
      }
    }

    if (action === 'sync-all') {
      const bookings = await prisma.booking.findMany({
        where: {
          status: {
            in: ['RESERVED', 'CONFIRMED', 'TOUR_CREATED'],
          },
        },
        include: {
          location: true,
          photobox: true,
        },
      });

      let synced = 0;
      let failed = 0;

      for (const booking of bookings) {
        try {
          await nextcloudCalendar.syncBookingToCalendar(booking);
          synced++;
        } catch (error) {
          console.error(`Failed to sync booking ${booking.id}:`, error);
          failed++;
        }
      }

      return NextResponse.json({ 
        success: true, 
        synced, 
        failed,
        total: bookings.length 
      });
    }

    if (action === 'remove-booking' && bookingId) {
      try {
        await nextcloudCalendar.removeBookingFromCalendar(bookingId);
        return NextResponse.json({ success: true, message: 'Booking removed from calendar' });
      } catch (error: any) {
        return NextResponse.json({ 
          success: false, 
          error: error.message 
        }, { status: 500 });
      }
    }

    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('Error in calendar sync:', error);
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}
