/**
 * POST   /api/admin/users/[userId]/brand-access  — grant a brand
 * DELETE /api/admin/users/[userId]/brand-access  — revoke a brand
 *
 * Body shape (both):
 *   { brandId: string, role?: "owner" | "admin" | "member" | "viewer" }
 *
 * Mirrors the per-member brand-access editor on the Settings → Team
 * tab, but exposed at the admin layer so superadmins can fix access
 * issues for any user without impersonating an org owner.
 *
 * Logged to ComplianceEvent under brand_access_granted /
 * brand_access_revoked.
 *
 * Superadmin-only.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getSuperadmin, requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";

export const dynamic = "force-dynamic";

export async function POST(req: Request, ctx: { params: { userId: string } }) {
  const denied = await requireSuperadmin();
  if (denied) return denied;
  const admin = await getSuperadmin();
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.json().catch(() => null) as { brandId?: string; role?: string } | null;
  const brandId = body?.brandId?.trim();
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  const role = body?.role === "admin" || body?.role === "viewer" || body?.role === "owner"
    ? body.role
    : "member";

  return NextResponse.json(await withAdminTiming("users.brand-grant", async () => {
    // Sanity: user + brand both exist.
    const [user, brand] = await Promise.all([
      prisma.user.findUnique({ where: { id: ctx.params.userId }, select: { id: true, email: true } }),
      prisma.brand.findUnique({ where: { id: brandId }, select: { id: true, orgId: true, name: true } }),
    ]);
    if (!user) return { ok: false as const, error: "User not found" };
    if (!brand) return { ok: false as const, error: "Brand not found" };

    // OrgMembership is the prerequisite for any brand-level grant.
    // If the user isn't in the brand's org yet, add them as a
    // member so the BrandMembership has something to anchor to.
    await prisma.orgMembership.upsert({
      where: { userId_orgId: { userId: user.id, orgId: brand.orgId } },
      create: { userId: user.id, orgId: brand.orgId, role: "member" },
      update: {},
    });

    await prisma.brandMembership.upsert({
      where: { userId_brandId: { userId: user.id, brandId: brand.id } },
      create: { userId: user.id, brandId: brand.id, role },
      update: { role },
    });

    await prisma.complianceEvent.create({
      data: {
        action: "brand_access_granted",
        brandId: brand.id,
        identifier: user.email,
        details: { role } as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

    return { ok: true as const };
  }));
}

export async function DELETE(req: Request, ctx: { params: { userId: string } }) {
  const denied = await requireSuperadmin();
  if (denied) return denied;
  const admin = await getSuperadmin();
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.json().catch(() => null) as { brandId?: string } | null;
  const brandId = body?.brandId?.trim();
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  return NextResponse.json(await withAdminTiming("users.brand-revoke", async () => {
    const user = await prisma.user.findUnique({
      where: { id: ctx.params.userId },
      select: { id: true, email: true },
    });
    if (!user) return { ok: false as const, error: "User not found" };

    const result = await prisma.brandMembership.deleteMany({
      where: { userId: user.id, brandId },
    });

    await prisma.complianceEvent.create({
      data: {
        action: "brand_access_revoked",
        brandId,
        identifier: user.email,
        details: { rowsRemoved: result.count } as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

    return { ok: true as const, removed: result.count };
  }));
}
