import { schema } from "@/db";
import type { Ctx } from "./auth";

/** ADM-003: every create, update, delete and integration action is logged. */
export async function audit(ctx: Pick<Ctx, "db" | "workspace" | "actor" | "ip">, action: string, objectType: string, objectId: string | null, before?: unknown, after?: unknown) {
  try {
    await ctx.db.insert(schema.auditLogs).values({
      workspaceId: ctx.workspace.id,
      actorType: ctx.actor.type,
      actorId: ctx.actor.id,
      actorName: ctx.actor.name,
      action, objectType, objectId,
      before: before === undefined ? null : strip(before),
      after: after === undefined ? null : strip(after),
      ip: ctx.ip ?? null,
    });
  } catch (e) {
    console.error("[audit] failed", e);
  }
}

const SENSITIVE = /password|secret|token|hashed|mfa/i;
function strip(v: unknown): unknown {
  if (Array.isArray(v)) return v.map(strip);
  if (v && typeof v === "object" && !(v instanceof Date)) {
    return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, SENSITIVE.test(k) ? "[redacted]" : strip(x)]));
  }
  return v;
}
