/**
 * GET /api/admin/analytics/radar?brandId=X
 * GET /api/admin/analytics/radar               (platform path)
 *
 *   - brandId path → detailed single-brand score with perDimension
 *                    deep-dive data + recommendations.
 *   - platform path → per-dimension averages + top/bottom
 *                    leaderboard + platformInsights (weakest /
 *                    strongest / most improved / needs attention /
 *                    distribution).
 *
 * Both paths return the same `dimensions` array (canonical labels).
 * Superadmin-only.
 */

import { NextResponse } from "next/server";
import { requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";
import {
  scoreAllBrands, scoreBrandDetailed,
  recommendationsForBrand, computePlatformInsights,
  RADAR_DIMENSIONS,
} from "@/lib/services/brand-radar";

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

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

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");

  if (brandId) {
    return NextResponse.json(await withAdminTiming("radar.brand", async () => {
      const detailed = await scoreBrandDetailed(brandId);
      if (!detailed) return { error: "not_found" as const };
      const recommendations = recommendationsForBrand(detailed);
      return { dimensions: RADAR_DIMENSIONS, score: detailed, recommendations };
    }));
  }

  return NextResponse.json(await withAdminTiming("radar.platform", async () => {
    const result = await scoreAllBrands();
    const sortedByHealth = [...result.brands].sort((a, b) => b.health - a.health);

    // Platform insights — weakest / strongest dim + distribution.
    // Computed in-process from the scored brands array so no extra
    // queries are needed.
    const platformInsights = result.brands.length > 0
      ? computePlatformInsights(result.brands, result.averages)
      : null;

    // Aggregate recommendations across all brands by taking each
    // brand's top rec (or none) and picking the three dimensions
    // that appear most often as "the weakest". Surfaces the
    // platform-wide where-to-focus without running detailed
    // recommendations per brand (a scored-full findMany per brand
    // isn't free at 200+ brands).
    const dimensionWeakness: Record<string, number> = {};
    for (const b of result.brands) {
      const sorted = [...RADAR_DIMENSIONS].sort(
        (a, c) => (b.scores[a.id] ?? 0) - (b.scores[c.id] ?? 0),
      );
      const weakest = sorted[0];
      if (weakest && b.scores[weakest.id] < 70) {
        dimensionWeakness[weakest.id] = (dimensionWeakness[weakest.id] ?? 0) + 1;
      }
    }

    return {
      dimensions: RADAR_DIMENSIONS,
      averages: result.averages,
      averageHealth: result.averageHealth,
      brandCount: result.brands.length,
      platformInsights,
      dimensionWeakness,
      leaderboard: {
        top: sortedByHealth.slice(0, 10).map((b) => ({
          brandId: b.brandId, brandName: b.brandName, domain: b.domain, health: b.health,
        })),
        bottom: sortedByHealth.slice(-10).reverse().map((b) => ({
          brandId: b.brandId, brandName: b.brandName, domain: b.domain, health: b.health,
        })),
      },
    };
  }));
}

