import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/auth';
import { getInstanceSettings, setSignupsOpen } from '@/lib/instanceSettings';

/**
 * GET  -> { signupsOpen }    any authenticated user (UI needs to know
 *                            whether to show the admin toggle / sign-up CTA)
 * POST -> { signupsOpen }    admin only; flips the singleton flag
 */

export async function GET() {
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  const settings = await getInstanceSettings();
  return NextResponse.json({ signupsOpen: settings.signupsOpen });
}

const bodySchema = z.object({ signupsOpen: z.boolean() });

export async function POST(request: NextRequest) {
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  if (!user.isAdmin) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
  }
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }
  const parsed = bodySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid body', details: parsed.error.errors },
      { status: 400 },
    );
  }
  const updated = await setSignupsOpen(parsed.data.signupsOpen);
  return NextResponse.json({ signupsOpen: updated.signupsOpen });
}
