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

// Full audit-log viewer feed — every action (not just auth), filterable by
// action / resource type / family / user / free-text, with the joined user
// email and family name for context.
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 action = searchParams.get("action")?.trim();
  const resourceType = searchParams.get("resourceType")?.trim();
  const familyId = searchParams.get("familyId")?.trim();
  const userId = searchParams.get("userId")?.trim();
  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 {
    const where: string[] = [`al.created_at > NOW() - make_interval(hours => $1)`];
    const params: unknown[] = [sinceHours];
    if (action) { params.push(action); where.push(`al.action = $${params.length}`); }
    if (resourceType) { params.push(resourceType); where.push(`al.resource_type = $${params.length}`); }
    if (familyId) { params.push(familyId); where.push(`al.family_id = $${params.length}::uuid`); }
    if (userId) { params.push(userId); where.push(`al.user_id = $${params.length}::uuid`); }
    if (q) { params.push(`%${q}%`); where.push(`(u.email ILIKE $${params.length} OR f.name ILIKE $${params.length} OR al.action ILIKE $${params.length})`); }
    const whereSql = where.join(" AND ");

    const events = await sql.unsafe(
      `SELECT al.id, al.action, al.resource_type, al.resource_id, al.ip_address,
              al.user_agent, al.metadata, al.created_at, al.user_id, al.family_id,
              u.email AS user_email, u.name AS user_name, f.name AS family_name
       FROM audit_log al
       LEFT JOIN users u ON u.id = al.user_id
       LEFT JOIN families f ON f.id = al.family_id
       WHERE ${whereSql}
       ORDER BY al.created_at DESC
       LIMIT ${limit}`,
      params as never[]
    );

    // Distinct action + resource-type values for the filter dropdowns.
    const actions = await sql`SELECT DISTINCT action FROM audit_log ORDER BY action`;
    const resourceTypes = await sql`SELECT DISTINCT resource_type FROM audit_log WHERE resource_type IS NOT NULL ORDER BY resource_type`;

    return NextResponse.json({
      events,
      actions: actions.map(r => (r as { action: string }).action),
      resourceTypes: resourceTypes.map(r => (r as { resource_type: string }).resource_type),
    });
  } catch (error) {
    console.error("Admin audit feed error:", error);
    return NextResponse.json({ events: [], actions: [], resourceTypes: [], error: String(error) });
  }
}
