import { NextResponse } from 'next/server';
import { OwnerTeamUpsertSchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { env } from '@/lib/env';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    await requireOwner('VIEWER');
    const members = await prisma.ownerTeamMember.findMany({ orderBy: { createdAt: 'asc' } });
    return NextResponse.json({
      bootstrapOwnerIds: env.OWNER_USER_IDS ?? [],
      members
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function PUT(request: Request) {
  try {
    const session = await requireOwner('OWNER');
    const body = OwnerTeamUpsertSchema.parse(await request.json());
    const before = await prisma.ownerTeamMember.findUnique({ where: { userId: body.userId } });
    const member = await prisma.ownerTeamMember.upsert({
      where: { userId: body.userId },
      create: {
        userId: body.userId,
        role: body.role,
        note: body.note ?? null
      },
      update: {
        role: body.role,
        note: body.note ?? null
      }
    });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: before ? 'team.update' : 'team.create',
      targetType: 'OwnerTeamMember',
      targetId: member.id,
      before,
      after: member
    });
    return NextResponse.json(member);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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