import {
  listAudit
} from "./chunk-OO3I5FOB.js";
import {
  requireAdmin,
  tenantFilter
} from "./chunk-K7DLILHK.js";
import {
  paginatedOk,
  routeWrap
} from "./chunk-QSHK4MUE.js";
import {
  badRequest
} from "./chunk-EZYKRG4W.js";

// src/handlers/audit.ts
function parseMs(v) {
  if (!v) return void 0;
  const n = Number(v);
  if (Number.isFinite(n)) return n;
  const t = Date.parse(v);
  return Number.isFinite(t) ? t : void 0;
}
var VALID_OUTCOMES = /* @__PURE__ */ new Set(["success", "denied", "failure"]);
function handleListAudit(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireAdmin(auth);
    const url = new URL(req.url);
    const limit = url.searchParams.get("limit");
    const cursor = url.searchParams.get("page") ?? void 0;
    const action = url.searchParams.get("action") ?? void 0;
    const actorKeyId = url.searchParams.get("actor_key_id") ?? void 0;
    const resourceType = url.searchParams.get("resource_type") ?? void 0;
    const resourceId = url.searchParams.get("resource_id") ?? void 0;
    const outcomeRaw = url.searchParams.get("outcome");
    const createdGte = parseMs(url.searchParams.get("created_at[gte]"));
    const createdLte = parseMs(url.searchParams.get("created_at[lte]"));
    let outcome;
    if (outcomeRaw != null) {
      if (!VALID_OUTCOMES.has(outcomeRaw)) {
        throw badRequest(
          `invalid outcome: ${outcomeRaw} (allowed: ${Array.from(VALID_OUTCOMES).join(",")})`
        );
      }
      outcome = outcomeRaw;
    }
    const requestedLimit = limit ? Number(limit) : 100;
    const data = listAudit({
      limit: requestedLimit,
      cursor,
      action,
      actor_key_id: actorKeyId,
      resource_type: resourceType,
      resource_id: resourceId,
      outcome,
      createdGte,
      createdLte,
      tenantFilter: tenantFilter(auth)
    });
    return paginatedOk(data, requestedLimit);
  });
}

export {
  handleListAudit
};
