import { NextResponse } from 'next/server';
import { readData, writeData, validateAuth } from '@/lib/cms';
import { events, joinRoles } from '@/lib/data/events';

export async function GET() {
  const evts = readData('events', events);
  const roles = readData('join-roles', joinRoles);
  return NextResponse.json({ events: evts, joinRoles: roles });
}

export async function POST(request: Request) {
  if (!validateAuth(request)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    if (body.events) writeData('events', body.events);
    if (body.joinRoles) writeData('join-roles', body.joinRoles);
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: 'Invalid data' }, { status: 400 });
  }
}
