import { NextRequest, NextResponse } from 'next/server'; import { getSession } from '@/lib/session'; import { db } from '@/lib/db'; import { bookings, courts, users } from '@/lib/db/schema'; import { eq, and } from 'drizzle-orm'; export async function GET(request: NextRequest) { try { const session = await getSession(); if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { searchParams } = new URL(request.url); const date = searchParams.get('date'); // Build query conditions const whereConditions = []; whereConditions.push(eq(bookings.status, 'active')); if (date) { whereConditions.push(eq(bookings.date, date)); } // Get all active bookings with user and court information const allBookings = await db .select({ id: bookings.id, courtId: bookings.courtId, date: bookings.date, startTime: bookings.startTime, endTime: bookings.endTime, status: bookings.status, notes: bookings.notes, createdAt: bookings.createdAt, court: { id: courts.id, name: courts.name, }, user: { id: users.id, name: users.name, surname: users.surname, }, }) .from(bookings) .innerJoin(courts, eq(bookings.courtId, courts.id)) .innerJoin(users, eq(bookings.userId, users.id)) .where(whereConditions.length > 1 ? and(...whereConditions) : whereConditions[0]); return NextResponse.json({ bookings: allBookings }); } catch (error) { console.error('Error fetching all bookings:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }