import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";

// Admin error tracker feed. Returns recent error events (filterable), a grouped
// "top errors" rollup, and headline counts.
export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const source = searchParams.get("source"); // client | server | null
  const level = searchParams.get("level");   // error | warn | fatal | null
  const q = searchParams.get("q")?.trim();
  const sinceHours = Math.min(Math.max(parseInt(searchParams.get("sinceHours") || "168", 10) || 168, 1), 24 * 90);
  const limit = Math.min(Math.max(parseInt(searchParams.get("limit") || "100", 10) || 100, 1), 500);

  try {
    // Build dynamic WHERE with positional params.
    const where: string[] = [`e.created_at > NOW() - make_interval(hours => $1)`];
    const params: unknown[] = [sinceHours];
    if (source === "client" || source === "server") { params.push(source); where.push(`e.source = $${params.length}`); }
    if (level === "error" || level === "warn" || level === "fatal") { params.push(level); where.push(`e.level = $${params.length}`); }
    if (q) { params.push(`%${q}%`); where.push(`e.message ILIKE $${params.length}`); }
    const whereSql = where.join(" AND ");

    const events = await sql.unsafe(
      `SELECT e.id, e.level, e.source, e.message, e.stack, e.url, e.digest,
              e.user_id, e.family_id, e.user_agent, e.created_at,
              u.email AS user_email, f.name AS family_name
       FROM error_events e
       LEFT JOIN users u ON u.id = e.user_id
       LEFT JOIN families f ON f.id = e.family_id
       WHERE ${whereSql}
       ORDER BY e.created_at DESC
       LIMIT ${limit}`,
      params as never[]
    );

    const grouped = await sql.unsafe(
      `SELECT message, source,
              COUNT(*)::int AS count,
              MAX(created_at) AS last_seen,
              MIN(created_at) AS first_seen
       FROM error_events e
       WHERE ${whereSql}
       GROUP BY message, source
       ORDER BY count DESC
       LIMIT 50`,
      params as never[]
    );

    const stats = await sql`
      SELECT
        COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '24 hours')::int AS last24h,
        COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '7 days')::int  AS last7d,
        COUNT(*) FILTER (WHERE source = 'client' AND created_at > NOW() - INTERVAL '7 days')::int AS client7d,
        COUNT(*) FILTER (WHERE source = 'server' AND created_at > NOW() - INTERVAL '7 days')::int AS server7d
      FROM error_events
    `;

    return NextResponse.json({
      events,
      grouped,
      stats: stats[0] || { last24h: 0, last7d: 0, client7d: 0, server7d: 0 },
    });
  } catch (error) {
    console.error("Admin errors feed error:", error);
    return NextResponse.json({ events: [], grouped: [], stats: { last24h: 0, last7d: 0, client7d: 0, server7d: 0 }, error: String(error) });
  }
}
