import { NextRequest, NextResponse } from "next/server";
import { requireAdmin, unauthorized } from "@/lib/admin-auth";
import { logAdminActivity } from "@/lib/admin-activity";
import { query } from "@/lib/db";
import { requestMeta } from "@/lib/request-meta";

type CountRow = { c: number };
type IpRow = { client_ip: string; request_count: number; errors: number };
type PathRow = { path_norm: string; request_count: number; avg_latency: number };
type BlockRow = {
  id: number;
  client_ip: string;
  reason: string;
  source: string;
  expires_at: string | null;
  created_at: string;
};
type RecentBlockHit = {
  client_ip: string;
  path_norm: string;
  status_code: number;
  created_at: string;
  rate_limit_action: string;
};

export async function GET(req: NextRequest) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();

  const meta = requestMeta(req);

  const [
    lastHour,
    lastHourBlocked,
    topIps,
    topPaths,
    blocklist,
    recentBlocks,
    byApp,
  ] = await Promise.all([
    query<CountRow[]>(
      `SELECT COUNT(*) AS c FROM http_request_events
       WHERE created_at >= NOW() - INTERVAL 1 HOUR`,
    ),
    query<CountRow[]>(
      `SELECT COUNT(*) AS c FROM http_request_events
       WHERE created_at >= NOW() - INTERVAL 1 HOUR
         AND rate_limit_action IN ('throttled','blocked')`,
    ),
    query<IpRow[]>(
      `SELECT client_ip,
              COUNT(*) AS request_count,
              SUM(CASE WHEN status_code >= 400 THEN 1 ELSE 0 END) AS errors
       FROM http_request_events
       WHERE created_at >= NOW() - INTERVAL 24 HOUR
       GROUP BY client_ip
       ORDER BY request_count DESC
       LIMIT 20`,
    ),
    query<PathRow[]>(
      `SELECT path_norm,
              COUNT(*) AS request_count,
              ROUND(AVG(latency_ms)) AS avg_latency
       FROM http_request_events
       WHERE created_at >= NOW() - INTERVAL 24 HOUR
       GROUP BY path_norm
       ORDER BY request_count DESC
       LIMIT 20`,
    ),
    query<BlockRow[]>(
      `SELECT id, client_ip, reason, source, expires_at, created_at
       FROM network_blocklist
       WHERE expires_at IS NULL OR expires_at > NOW()
       ORDER BY created_at DESC
       LIMIT 100`,
    ),
    query<RecentBlockHit[]>(
      `SELECT client_ip, path_norm, status_code, created_at, rate_limit_action
       FROM http_request_events
       WHERE rate_limit_action IN ('throttled','blocked')
       ORDER BY created_at DESC
       LIMIT 30`,
    ),
    query<{ app: string; c: number }[]>(
      `SELECT app, COUNT(*) AS c FROM http_request_events
       WHERE created_at >= NOW() - INTERVAL 1 HOUR
       GROUP BY app`,
    ),
  ]);

  const lastHourCount = Number(lastHour[0]?.c || 0);
  const rpsApprox = Math.round((lastHourCount / 3600) * 100) / 100;

  await logAdminActivity({
    adminId: admin.id,
    username: admin.username,
    action: "view_network",
    resource: "network",
    outcome: "success",
    ip: meta.ip,
    userAgent: meta.userAgent,
  });

  return NextResponse.json({
    ok: true,
    summary: {
      last_hour_requests: lastHourCount,
      last_hour_throttled_or_blocked: Number(lastHourBlocked[0]?.c || 0),
      approx_rps: rpsApprox,
      by_app: byApp,
    },
    top_ips: topIps,
    top_paths: topPaths,
    blocklist,
    recent_blocks: recentBlocks,
  });
}
