import { NextResponse } from 'next/server';
import { GlobalUserBlacklistSchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
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');
    const users = await prisma.globalUserBlacklist.findMany({ orderBy: { createdAt: 'desc' } });
    return NextResponse.json({ users });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function PUT(request: Request) {
  try {
    const session = await requireOwner('SUPPORT');
    const body = GlobalUserBlacklistSchema.parse(await request.json());
    const before = await prisma.globalUserBlacklist.findUnique({ where: { userId: body.userId } });
    const row = await prisma.globalUserBlacklist.upsert({
      where: { userId: body.userId },
      create: {
        userId: body.userId,
        reason: body.reason ?? null,
        note: body.note ?? null,
        createdById: session.user.id
      },
      update: {
        reason: body.reason ?? null,
        note: body.note ?? null
      }
    });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: before ? 'users.blacklist.update' : 'users.blacklist.create',
      targetType: 'GlobalUserBlacklist',
      targetId: row.id,
      before,
      after: row
    });
    return NextResponse.json(row);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function DELETE(request: Request) {
  try {
    const session = await requireOwner('SUPPORT');
    const userId = new URL(request.url).searchParams.get('userId');
    if (!userId) {
      return NextResponse.json({ error: 'userId required' }, { status: 400 });
    }
    const before = await prisma.globalUserBlacklist.findUnique({ where: { userId } });
    if (!before) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    await prisma.globalUserBlacklist.delete({ where: { userId } });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: 'users.blacklist.delete',
      targetType: 'GlobalUserBlacklist',
      targetId: before.id,
      before
    });
    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
