import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth/session";
import { getTenantDetail } from "@/lib/db/queries/tenants";
import { logActivity } from "@/lib/db/audit";

// Route handler en lecture pure : retourne le détail d'un tenant en JSON
// pour la modal client. Auth via cookie session déjà vérifiée par proxy.ts
// mais on re-check le flag is_superadmin pour défense en profondeur.

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getSession();
  if (!session?.user.is_superadmin) {
    return NextResponse.json(
      { success: false, error: "FORBIDDEN" },
      { status: 403 },
    );
  }

  const { id: idStr } = await params;
  const id = Number.parseInt(idStr, 10);
  if (!Number.isFinite(id) || id <= 0) {
    return NextResponse.json(
      { success: false, error: "INVALID_ID" },
      { status: 400 },
    );
  }

  try {
    const detail = await getTenantDetail(id);
    if (!detail) {
      return NextResponse.json(
        { success: false, error: "NOT_FOUND" },
        { status: 404 },
      );
    }
    void logActivity({
      type: "superadmin.tenant_detail_view",
      title: `Détail tenant #${id} (${detail.slug})`,
      tenant_id: id,
      user_id: session.user.id,
    });
    return NextResponse.json({ success: true, data: detail });
  } catch (err) {
    return NextResponse.json(
      {
        success: false,
        error: "DB_ERROR",
        message: err instanceof Error ? err.message : "unknown",
      },
      { status: 500 },
    );
  }
}
