/**
 * GET /api/admin/brand-health/check-now
 *
 * Manual trigger for the brand health detector. Returns full per-brand
 * results as JSON so you can call it from DevTools to verify logic.
 * Superadmin-only.
 *
 * Example:
 *   fetch("/api/admin/brand-health/check-now").then(r => r.json()).then(console.log)
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { runBrandHealthCheck } from "@/lib/services/brand-health-detector";

export const dynamic = "force-dynamic";
export const maxDuration = 180;

export async function GET() {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const results = await runBrandHealthCheck();

  const summary = {
    total: results.length,
    skipped: results.filter((r) => r.skipped).length,
    healthy: results.filter((r) => !r.skipped && r.action === "none").length,
    opened: results.filter((r) => r.action === "opened").length,
    escalatedToDown: results.filter((r) => r.action === "escalated_to_down").length,
    resolved: results.filter((r) => r.action === "resolved").length,
    updated: results.filter((r) => r.action === "updated").length,
  };

  return NextResponse.json({ summary, results });
}
