import { NextResponse } from 'next/server';
import { FeatureFlagUpsertSchema } 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 flags = await prisma.featureFlag.findMany({ orderBy: { key: 'asc' } });
    return NextResponse.json({ flags });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function PUT(request: Request) {
  try {
    const session = await requireOwner('ADMIN');
    const body = FeatureFlagUpsertSchema.parse(await request.json());
    const before = await prisma.featureFlag.findUnique({ where: { key: body.key } });
    const flag = await prisma.featureFlag.upsert({
      where: { key: body.key },
      create: {
        key: body.key,
        enabled: body.enabled,
        rolloutPercent: body.rolloutPercent,
        whitelistGuildIds: body.whitelistGuildIds
      },
      update: {
        enabled: body.enabled,
        rolloutPercent: body.rolloutPercent,
        whitelistGuildIds: body.whitelistGuildIds
      }
    });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: before ? 'flags.update' : 'flags.create',
      targetType: 'FeatureFlag',
      targetId: flag.id,
      before,
      after: flag
    });
    return NextResponse.json(flag);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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