import { NextResponse } from 'next/server';
import { BotAboutConfigPatchSchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
import { getAboutConfig, updateAboutConfig } from '@/lib/owner-about';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    await requireOwner('VIEWER');
    return NextResponse.json(await getAboutConfig());
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function PATCH(request: Request) {
  try {
    const session = await requireOwner('ADMIN');
    const body = BotAboutConfigPatchSchema.parse(await request.json());
    const before = await getAboutConfig();
    const after = await updateAboutConfig(body);
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: 'about.update',
      targetType: 'BotAboutConfig',
      targetId: 'singleton',
      before,
      after
    });
    return NextResponse.json(after);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
