-- =====================================================
-- ORBIQUANT IA - WALLET AUDIT LOG TABLE
-- =====================================================
-- Description: Audit trail for all wallet state changes
-- Schema: financial
-- =====================================================

CREATE TABLE financial.wallet_audit_log (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Wallet referencia
  wallet_id UUID NOT NULL REFERENCES financial.wallets(id) ON DELETE CASCADE,

  -- Acción
  action financial.audit_action NOT NULL,

  -- Actor (quien realizó el cambio)
  actor_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  actor_type VARCHAR(50) DEFAULT 'user', -- user, system, admin, api

  -- Cambios registrados
  old_values JSONB,
  new_values JSONB,

  -- Balance snapshot
  balance_before DECIMAL(20,8),
  balance_after DECIMAL(20,8),

  -- Transacción relacionada (si aplica)
  transaction_id UUID REFERENCES financial.wallet_transactions(id) ON DELETE SET NULL,

  -- Contexto
  reason TEXT,
  metadata JSONB DEFAULT '{}',

  -- IP y user agent (para auditoría de seguridad)
  ip_address INET,
  user_agent TEXT,

  -- Timestamp
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraints
  CONSTRAINT balance_change_has_amounts CHECK (
    (action = 'balance_updated' AND balance_before IS NOT NULL AND balance_after IS NOT NULL) OR
    (action != 'balance_updated')
  )
);

-- Indexes
CREATE INDEX idx_wal_wallet_id ON financial.wallet_audit_log(wallet_id);
CREATE INDEX idx_wal_action ON financial.wallet_audit_log(action);
CREATE INDEX idx_wal_actor_id ON financial.wallet_audit_log(actor_id) WHERE actor_id IS NOT NULL;
CREATE INDEX idx_wal_created_at ON financial.wallet_audit_log(created_at DESC);
CREATE INDEX idx_wal_wallet_created ON financial.wallet_audit_log(wallet_id, created_at DESC);
CREATE INDEX idx_wal_transaction_id ON financial.wallet_audit_log(transaction_id) WHERE transaction_id IS NOT NULL;

-- Partitioning hint: Esta tabla puede crecer mucho, considerar particionamiento por created_at
-- PARTITION BY RANGE (created_at);

-- Comments
COMMENT ON TABLE financial.wallet_audit_log IS 'Immutable audit trail for all wallet state changes';
COMMENT ON COLUMN financial.wallet_audit_log.action IS 'Type of action performed on wallet';
COMMENT ON COLUMN financial.wallet_audit_log.actor_id IS 'User who performed the action (NULL for system actions)';
COMMENT ON COLUMN financial.wallet_audit_log.actor_type IS 'Type of actor: user, system, admin, api';
COMMENT ON COLUMN financial.wallet_audit_log.old_values IS 'JSON snapshot of values before change';
COMMENT ON COLUMN financial.wallet_audit_log.new_values IS 'JSON snapshot of values after change';
COMMENT ON COLUMN financial.wallet_audit_log.metadata IS 'Additional context and metadata';
