/**
 * GET /api/admin/organizations — list all orgs (paginated, searchable).
 */
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const auth = await requireAdmin();
  if (!auth.ok) return NextResponse.json({ error: "Forbidden" }, { status: auth.status });
  const { searchParams } = new URL(req.url);
  const page = Math.max(1, Number(searchParams.get("page") || 1));
  const q = searchParams.get("q") || "";
  const take = 50;
  const where = q ? { name: { contains: q, mode: "insensitive" as const } } : {};

  const [orgs, total] = await Promise.all([
    prisma.organization.findMany({
      where, skip: (page - 1) * take, take,
      include: { _count: { select: { brands: true, memberships: true } } },
      orderBy: { createdAt: "desc" },
    }),
    prisma.organization.count({ where }),
  ]);

  return NextResponse.json({ organizations: orgs, total, page, pages: Math.ceil(total / take) });
}
