import { NextResponse } from 'next/server';
import { BotPresenceConfigPatchSchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { getPresenceConfig, updatePresenceConfig } from '@/lib/owner-presence';
import { prisma } from '@/lib/prisma';

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

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