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

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

    const searchParams = req.nextUrl.searchParams;
    const start = searchParams.get('start');
    const end = searchParams.get('end');

    const where: any = {};
    
    if (start && end) {
      where.eventDate = {
        gte: new Date(start),
        lte: new Date(end),
      };
    }

    const bookings = await prisma.booking.findMany({
      where,
      include: {
        location: true,
        photobox: true,
        tour: true,
      },
      orderBy: { eventDate: 'asc' },
    });

    const events = bookings.map((booking) => ({
      id: booking.id,
      title: `${booking.customerName} - ${booking.location.name}`,
      start: booking.eventDate,
      end: new Date(new Date(booking.eventDate).getTime() + 4 * 60 * 60 * 1000),
      resource: {
        bookingId: booking.id,
        status: booking.status,
        customerName: booking.customerName,
        customerEmail: booking.customerEmail,
        locationName: booking.location.name,
        photoboxName: booking.photobox?.name || 'Keine Box',
        tourId: booking.tourId,
        eventType: booking.eventType,
      },
    }));

    return NextResponse.json({ events });
  } catch (error) {
    console.error('Error fetching calendar events:', error);
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}
