import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { courts } from '@/lib/db/schema'; import { eq } from 'drizzle-orm'; import { getSession } from '@/lib/session'; export async function PUT(request: NextRequest, { params }: { params: { id: string } }) { try { const session = await getSession(); if (!session || session.role !== 'admin') { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { name, isActive } = await request.json(); const courtId = params.id; if (!name) { return NextResponse.json({ error: 'Court name is required' }, { status: 400 }); } // Check if court exists const existing = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1); if (existing.length === 0) { return NextResponse.json({ error: 'Court not found' }, { status: 404 }); } // Update court const [updatedCourt] = await db .update(courts) .set({ name, isActive: isActive !== undefined ? isActive : true, updatedAt: new Date(), }) .where(eq(courts.id, courtId)) .returning(); return NextResponse.json({ court: updatedCourt, message: 'Court updated successfully', }); } catch (error) { console.error('Error updating court:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } } export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) { try { const session = await getSession(); if (!session || session.role !== 'admin') { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const courtId = params.id; // Check if court exists const existing = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1); if (existing.length === 0) { return NextResponse.json({ error: 'Court not found' }, { status: 404 }); } // Delete court (this will cascade to bookings due to foreign key) await db.delete(courts).where(eq(courts.id, courtId)); return NextResponse.json({ message: 'Court deleted successfully' }); } catch (error) { console.error('Error deleting court:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }