/**
 * POST /api/admin/brands/[brandId]/transfer
 * Transfer a brand to a different organization (by destination
 * owner email). The destination user must exist and have an
 * OrgMembership; we move the brand to that user's first org.
 *
 * Body: { ownerEmail: "new-owner@example.com" }
 */

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: { brandId: 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 { ownerEmail?: string } | null;
  const email = body?.ownerEmail?.trim().toLowerCase();
  if (!email) return NextResponse.json({ error: "ownerEmail required" }, { status: 400 });

  return NextResponse.json(await withAdminTiming("brands.transfer", async () => {
    const targetUser = await prisma.user.findUnique({
      where: { email },
      include: {
        memberships: {
          where: { role: { in: ["owner", "admin"] } },
          orderBy: { createdAt: "asc" },
          take: 1,
        },
      },
    });
    if (!targetUser) return { error: "no_user" as const, message: "No user with that email." };
    const destOrgId = targetUser.memberships[0]?.orgId;
    if (!destOrgId) return { error: "no_org" as const, message: "Target user isn't owner/admin of any org." };

    const brand = await prisma.brand.update({
      where: { id: ctx.params.brandId },
      data: { orgId: destOrgId },
      select: { id: true, name: true, orgId: true },
    });

    // Grant the new owner explicit BrandMembership too so the
    // sidebar / brand-access filter behave consistently across
    // owner / admin / member roles.
    await prisma.brandMembership.upsert({
      where: { userId_brandId: { userId: targetUser.id, brandId: brand.id } },
      create: { userId: targetUser.id, brandId: brand.id, role: "owner" },
      update: { role: "owner" },
    });

    await prisma.complianceEvent.create({
      data: {
        action: "brand_transferred",
        brandId: brand.id,
        identifier: email,
        details: { newOrgId: destOrgId, newOwnerUserId: targetUser.id } as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

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