60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
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 GET(request: NextRequest) {
|
|
try {
|
|
const session = await getSession();
|
|
if (!session) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
// Regular users see only active courts, admins see all
|
|
const allCourts = await db
|
|
.select()
|
|
.from(courts)
|
|
.where(session.role === 'admin' ? undefined : eq(courts.isActive, true));
|
|
|
|
return NextResponse.json({ courts: allCourts });
|
|
} catch (error) {
|
|
console.error('Error fetching courts:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await getSession();
|
|
if (!session || session.role !== 'admin') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { name, isActive } = await request.json();
|
|
|
|
if (!name) {
|
|
return NextResponse.json({ error: 'Court name is required' }, { status: 400 });
|
|
}
|
|
|
|
const [newCourt] = await db
|
|
.insert(courts)
|
|
.values({
|
|
id: crypto.randomUUID(),
|
|
name,
|
|
isActive: isActive !== undefined ? isActive : true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
})
|
|
.returning();
|
|
|
|
return NextResponse.json({
|
|
court: newCourt,
|
|
message: 'Court created successfully',
|
|
});
|
|
} catch (error) {
|
|
console.error('Error creating court:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|