import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/admin/auth";
import { getCloudinaryStatus, pingCloudinary } from "@/lib/cloudinary";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
 * GET /api/admin/media/health
 * Admin-only Cloudinary diagnostic. Returns ONLY safe state — never the API key
 * or secret. `?ping=1` additionally does a real credential round-trip to Cloudinary.
 */
export async function GET(req: NextRequest) {
  try {
    await requireAuth(req);
  } catch (err: any) {
    return NextResponse.json(
      { error: err.message || "Unauthorized" },
      { status: err.status || 401 }
    );
  }

  const status = getCloudinaryStatus();
  const wantPing = new URL(req.url).searchParams.get("ping") === "1";

  let ping: { ok: boolean; error?: string } | undefined;
  if (wantPing && status.configured) {
    ping = await pingCloudinary();
  }

  return NextResponse.json({
    storage: "cloudinary",
    cloudinaryConfigured: status.configured,
    hasCloudName: status.hasCloudName,
    hasApiKey: status.hasApiKey,
    hasApiSecret: status.hasApiSecret,
    cloudName: status.cloudName, // not secret — appears in every public delivery URL
    localFallback: false,
    ...(ping ? { credentialsAccepted: ping.ok, pingError: ping.ok ? undefined : ping.error } : {}),
  });
}
