/**
 * DELETE /api/client-portal/users/[userId] — deactivate a client user.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function DELETE(_req: Request, { params }: { params: { userId: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const clientUser = await prisma.clientUser.findUnique({
    where: { id: params.userId },
    include: { portal: { include: { brand: { include: { organization: { include: { memberships: true } } } } } } },
  });
  if (!clientUser) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!clientUser.portal.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  await prisma.clientUser.update({ where: { id: params.userId }, data: { isActive: false } });
  return NextResponse.json({ ok: true });
}
