import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import { getDashboardMetrics, getPrometheusMetrics } from "@/lib/metrics";
import { getSamplingConfig } from "@/lib/log-sampler";
import { logger } from "@/lib/logger";
// Convex routing (WU-13): in-memory metrics, no DB data. No Convex routing needed.

/**
 * GET /api/staff/dashboard/metrics
 *
 * Returns application metrics for the staff logging dashboard.
 * Requires ADMIN or SUPER_ADMIN role.
 *
 * Query params:
 * - format=prometheus  — returns Prometheus text format
 * - format=json        — returns structured JSON (default)
 */
export async function GET(request: NextRequest) {
  try {
    const user = await validateStaffSession();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 },
      );
    }

    const format = request.nextUrl.searchParams.get("format") || "json";

    if (format === "prometheus") {
      return new NextResponse(getPrometheusMetrics(), {
        headers: { "Content-Type": "text/plain; charset=utf-8" },
      });
    }

    const metrics = getDashboardMetrics();
    const sampling = getSamplingConfig();

    return NextResponse.json({
      metrics,
      sampling,
      environment: process.env.NODE_ENV,
      logLevel: process.env.LOG_LEVEL || "info",
    });
  } catch (error) {
    logger.error("Failed to fetch metrics", error);
    return NextResponse.json(
      { error: "Failed to fetch metrics" },
      { status: 500 },
    );
  }
}
