/**
 * POST /api/admin/organizations/[orgId]/plan
 *
 * Updates a single organization's plan field. Superadmin-only.
 * Writes a ComplianceEvent audit row with actor, target org, and
 * before/after plan values.
 *
 * Body: { plan: string }
 * Response: { id, name, plan, before }
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getSuperadmin, requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";

export const dynamic = "force-dynamic";

const VALID_PLANS = ["free", "trial", "growth", "professional", "agency", "agency_pro", "enterprise"];

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

  const { orgId } = params;

  const body = await req.json().catch(() => ({})) as { plan?: string };
  const newPlan = typeof body.plan === "string" ? body.plan.trim() : "";

  if (!VALID_PLANS.includes(newPlan)) {
    return NextResponse.json(
      { error: `Invalid plan. Must be one of: ${VALID_PLANS.join(", ")}` },
      { status: 400 },
    );
  }

  return NextResponse.json(
    await withAdminTiming("admin.org-plan-update", async () => {
      const org = await prisma.organization.findUnique({
        where: { id: orgId },
        select: { id: true, name: true, plan: true },
      });
      if (!org) {
        return NextResponse.json({ error: "Organization not found" }, { status: 404 });
      }

      const before = org.plan;

      await prisma.organization.update({
        where: { id: orgId },
        data: { plan: newPlan },
      });

      await prisma.complianceEvent.create({
        data: {
          action: "org_plan_change",
          details: {
            orgId,
            orgName: org.name,
            before,
            after: newPlan,
          } as object,
          requestedBy: admin.userId,
        },
      }).catch(() => {});

      return { id: orgId, name: org.name, plan: newPlan, before };
    }),
  );
}
