import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { courtBlocks, courts } from '@/lib/db/schema'; import { eq, gte, and, lte, asc } from 'drizzle-orm'; import { getSession } from '@/lib/session'; 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 startDate = searchParams.get('startDate'); const endDate = searchParams.get('endDate'); // Default to today if no start date provided const today = new Date().toISOString().split('T')[0]; const queryStartDate = startDate || today; // Default to 60 days ahead if no end date provided (8 weeks + buffer) const defaultEndDate = new Date(); defaultEndDate.setDate(defaultEndDate.getDate() + 60); const queryEndDate = endDate || defaultEndDate.toISOString().split('T')[0]; // Fetch blocks with court info for the date range const blocks = await db .select({ id: courtBlocks.id, courtId: courtBlocks.courtId, date: courtBlocks.date, startTime: courtBlocks.startTime, endTime: courtBlocks.endTime, reason: courtBlocks.reason, court: { id: courts.id, name: courts.name, }, }) .from(courtBlocks) .leftJoin(courts, eq(courtBlocks.courtId, courts.id)) .where(and(gte(courtBlocks.date, queryStartDate), lte(courtBlocks.date, queryEndDate))) .orderBy(asc(courtBlocks.date), asc(courtBlocks.startTime)); return NextResponse.json({ blocks }); } catch (error) { console.error('Error fetching blocks:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }