import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { prisma } from "@/lib/prisma";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { getMetricsSnapshot } from "@/modules/metrics/collector";
import { getQueueDepth } from "@/workers/rpa/queue";

/** GET /api/metrics/dashboard — GD-4 汇总指标（task-102） */
export async function GET(request: Request) {
  try {
    parseAdminAuth(request);
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const [metrics, queueDepth, openAlertsCount] = await Promise.all([
    getMetricsSnapshot(),
    getQueueDepth(),
    prisma.alertLog.count({ where: { status: "open" } }),
  ]);

  return ok({
    api_success_rate: metrics.api_success_rate,
    rpa_success_rate: metrics.rpa_success_rate,
    realtime_rate: metrics.realtime_rate,
    cache_hit_rate: metrics.cache_hit_rate,
    p95_latency_ms: metrics.p95_latency_ms,
    queue_depth: queueDepth,
    open_alerts_count: openAlertsCount,
    counters: metrics.counters,
    latency_sample_count: metrics.latency_sample_count,
  });
}
