import { getDb } from "@/core/db/client";
import { auditLogs } from "@/core/db/schema";

type AuditInput = {
  actorUserId?: string | null;
  tenantId?: string | null;
  action: string;
  targetType?: string;
  targetId?: string;
  ipAddress?: string | null;
  userAgent?: string | null;
  metadata?: Record<string, unknown>;
};

/** Record privileged / sensitive actions. Never log secrets or passwords. */
export async function writeAuditLog(input: AuditInput) {
  const db = getDb();
  await db.insert(auditLogs).values({
    actorUserId: input.actorUserId ?? null,
    tenantId: input.tenantId ?? null,
    action: input.action,
    targetType: input.targetType,
    targetId: input.targetId,
    ipAddress: input.ipAddress ?? null,
    userAgent: input.userAgent ?? null,
    metadata: input.metadata ?? {},
  });
}
