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 AuditRow = {
  id: number;
  step: string;
  channel: string;
  outcome: string;
  ip: string | null;
  user_agent: string | null;
  meta: unknown;
  created_at: string;
};

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

  const meta = requestMeta(req);
  const sp = req.nextUrl.searchParams;
  const limit = Math.min(200, Math.max(1, Number(sp.get("limit") || 100)));
  const step = sp.get("step") || "";
  const outcome = sp.get("outcome") || "";
  const channel = sp.get("channel") || "";

  const clauses: string[] = [];
  const params: Record<string, unknown> = {};

  if (step) {
    clauses.push("step = :step");
    params.step = step;
  }
  if (outcome) {
    clauses.push("outcome = :outcome");
    params.outcome = outcome;
  }
  if (channel) {
    clauses.push("channel = :channel");
    params.channel = channel;
  }

  const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";

  const rows = await query<AuditRow[]>(
    `SELECT id, step, channel, outcome, ip, user_agent, meta, created_at
     FROM audit_logs
     ${where}
     ORDER BY created_at DESC
     LIMIT ${limit}`,
    params,
  );

  await logAdminActivity({
    adminId: admin.id,
    username: admin.username,
    action: "view_website_audit",
    resource: "website-audit",
    outcome: "success",
    ip: meta.ip,
    userAgent: meta.userAgent,
  });

  return NextResponse.json({ ok: true, logs: rows });
}
