34 lines
1.4 KiB
TypeScript
34 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getCurrentUser } from '@/lib/server/auth';
|
|
import { recordAudit } from '@/lib/server/audit';
|
|
import { adminListServices, serviceSchema, upsertService } from '@/lib/server/booking';
|
|
|
|
export const dynamic = 'force-dynamic';
|
|
|
|
async function requireAdminApi() {
|
|
const user = await getCurrentUser();
|
|
if (!user) return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
|
if (user.role !== 'admin') return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
|
|
return { user };
|
|
}
|
|
|
|
export async function GET() {
|
|
const auth = await requireAdminApi();
|
|
if (auth.error) return auth.error;
|
|
return NextResponse.json({ services: await adminListServices() });
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
const auth = await requireAdminApi();
|
|
if (auth.error) return auth.error;
|
|
const parsed = serviceSchema.safeParse(await request.json().catch(() => ({})));
|
|
if (!parsed.success) return NextResponse.json({ error: 'Invalid service.' }, { status: 400 });
|
|
try {
|
|
const service = await upsertService(parsed.data);
|
|
await recordAudit({ actorId: auth.user!.id, action: 'service.create', target: service.slug });
|
|
return NextResponse.json({ service }, { status: 201 });
|
|
} catch {
|
|
return NextResponse.json({ error: 'Could not create service (is the slug unique?).' }, { status: 409 });
|
|
}
|
|
}
|