import { auditLog, createDb } from '@bmm/db';

const db = createDb();

export interface AuditInput {
  orgId?: string;
  userId?: string;
  action: string;
  resourceType?: string;
  resourceId?: string;
  metadata?: Record<string, unknown>;
  ipAddress?: string;
}

export async function audit(input: AuditInput): Promise<void> {
  try {
    await db.insert(auditLog).values({
      orgId: input.orgId ?? null,
      userId: input.userId ?? null,
      action: input.action,
      resourceType: input.resourceType ?? null,
      resourceId: input.resourceId ?? null,
      metadata: input.metadata ?? null,
      ipAddress: input.ipAddress ?? null,
    });
  } catch (err) {
    // Audit failures must never block the request path.
    // eslint-disable-next-line no-console
    console.error('[audit] failed to write entry:', err);
  }
}
