import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";

async function assertSuperAdmin(userId: string) {
  const user = await prisma.user.findUnique({ where: { id: userId }, select: { isSuperAdmin: true } });
  return user?.isSuperAdmin === true;
}

export async function GET(req: NextRequest) {
  try {
    const session = await auth();
    const userId = session?.user?.id;
    if (!userId) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
    if (!(await assertSuperAdmin(userId))) return NextResponse.json({ success: false, error: "Accès refusé" }, { status: 403 });

    const { searchParams } = new URL(req.url);
    const search = searchParams.get("search")?.trim() ?? "";
    const plan   = searchParams.get("plan") ?? "";
    const page   = Math.max(1, parseInt(searchParams.get("page") ?? "1"));
    const limit  = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "25")));

    const where: Prisma.OrganizationWhereInput = {
      ...(search && {
        OR: [
          { name: { contains: search, mode: "insensitive" } },
          { slug: { contains: search, mode: "insensitive" } },
          { country: { contains: search, mode: "insensitive" } },
        ],
      }),
      ...(plan && { subscription: { plan: plan as any } }),
    };

    const [orgs, total] = await prisma.$transaction([
      prisma.organization.findMany({
        where,
        include: {
          subscription: { select: { plan: true, status: true, currentPeriodEnd: true } },
          _count: { select: { members: true, invoices: true, customers: true } },
        },
        orderBy: { createdAt: "desc" },
        skip: (page - 1) * limit,
        take: limit,
      }),
      prisma.organization.count({ where }),
    ]);

    return NextResponse.json({
      success: true,
      data: orgs,
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (err: any) {
    console.error("[GET /api/admin/organizations]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur", detail: err?.message }, { status: 500 });
  }
}
