import { NextResponse } from 'next/server';
import { Role } from '@prisma/client';
import { requireAuth } from '../../../../lib/jwt';
import { getSiteSettings, updateSiteSettings } from '../../../../lib/settings';

export async function GET(req: Request) {
  try {
    const auth = await requireAuth(req);
    if (auth.role !== Role.ADMIN) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const settings = await getSiteSettings();
    return NextResponse.json({ settings });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Load settings error', error);
    return NextResponse.json({ error: 'Failed to load settings' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const auth = await requireAuth(req);
    if (auth.role !== Role.ADMIN) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await req.json();
    const payload: Parameters<typeof updateSiteSettings>[0] = {};
    if (body.requireLoginForContactDetails !== undefined) {
      payload.requireLoginForContactDetails = Boolean(body.requireLoginForContactDetails);
    }
    const settings = await updateSiteSettings(payload);

    return NextResponse.json({ settings });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Save settings error', error);
    return NextResponse.json({ error: 'Failed to save settings' }, { status: 500 });
  }
}

export const dynamic = 'force-dynamic';
