import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const locationSlug = searchParams.get('location');
    const model = searchParams.get('model');
    const date = searchParams.get('date');

    if (!locationSlug || !model || !date) {
      return NextResponse.json(
        { error: 'Missing required parameters: location, model, date' },
        { status: 400 }
      );
    }

    const location = await prisma.location.findUnique({
      where: { slug: locationSlug },
    });

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

    const eventDate = new Date(date);
    const startOfDay = new Date(eventDate);
    startOfDay.setHours(0, 0, 0, 0);
    const endOfDay = new Date(eventDate);
    endOfDay.setHours(23, 59, 59, 999);

    const totalPhotoboxes = await prisma.photobox.count({
      where: {
        locationId: location.id,
        model: model as any,
        active: true,
      },
    });

    const bookedPhotoboxes = await prisma.booking.count({
      where: {
        locationId: location.id,
        photobox: {
          model: model as any,
        },
        eventDate: {
          gte: startOfDay,
          lte: endOfDay,
        },
        status: {
          in: ['RESERVED', 'CONFIRMED'],
        },
      },
    });

    const available = totalPhotoboxes - bookedPhotoboxes;
    const isAvailable = available > 0;
    const isLastOne = available === 1;

    return NextResponse.json({
      available: isAvailable,
      count: available,
      total: totalPhotoboxes,
      isLastOne,
      message: isAvailable
        ? isLastOne
          ? 'Nur noch 1 Fotobox verfügbar!'
          : `${available} Fotoboxen verfügbar`
        : 'Leider ausgebucht',
    });
  } catch (error) {
    console.error('Availability check error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
