-- =====================================================
-- ORBIQUANT IA - WALLET LIMITS TABLE
-- =====================================================
-- Description: Configurable limits and thresholds for wallets
-- Schema: financial
-- =====================================================
-- Separado de wallets para permitir límites más complejos
-- y dinámicos basados en plan, nivel de verificación, etc.
-- =====================================================

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

  -- Wallet o configuración global
  wallet_id UUID REFERENCES financial.wallets(id) ON DELETE CASCADE,
  wallet_type financial.wallet_type, -- Para límites por tipo de wallet
  subscription_plan financial.subscription_plan, -- Para límites por plan

  -- Límites de transacción única
  min_deposit DECIMAL(15,2),
  max_deposit DECIMAL(15,2),
  min_withdrawal DECIMAL(15,2),
  max_withdrawal DECIMAL(15,2),
  min_transfer DECIMAL(15,2),
  max_transfer DECIMAL(15,2),

  -- Límites periódicos
  daily_deposit_limit DECIMAL(15,2),
  daily_withdrawal_limit DECIMAL(15,2),
  daily_transfer_limit DECIMAL(15,2),

  weekly_deposit_limit DECIMAL(15,2),
  weekly_withdrawal_limit DECIMAL(15,2),
  weekly_transfer_limit DECIMAL(15,2),

  monthly_deposit_limit DECIMAL(15,2),
  monthly_withdrawal_limit DECIMAL(15,2),
  monthly_transfer_limit DECIMAL(15,2),

  -- Límites de volumen
  max_pending_transactions INTEGER,
  max_daily_transaction_count INTEGER,

  -- Balance limits
  min_balance DECIMAL(15,2) DEFAULT 0,
  max_balance DECIMAL(15,2),

  -- Moneda de los límites
  currency financial.currency_code NOT NULL DEFAULT 'USD',

  -- Prioridad (mayor número = mayor prioridad)
  priority INTEGER DEFAULT 0,

  -- Vigencia
  active BOOLEAN DEFAULT true,
  valid_from TIMESTAMPTZ DEFAULT NOW(),
  valid_to TIMESTAMPTZ,

  -- Metadata
  description TEXT,
  metadata JSONB DEFAULT '{}',

  -- Timestamps
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraints
  CONSTRAINT wallet_or_type_or_plan CHECK (
    (wallet_id IS NOT NULL AND wallet_type IS NULL AND subscription_plan IS NULL) OR
    (wallet_id IS NULL AND wallet_type IS NOT NULL AND subscription_plan IS NULL) OR
    (wallet_id IS NULL AND wallet_type IS NULL AND subscription_plan IS NOT NULL)
  ),
  CONSTRAINT positive_limits CHECK (
    (min_deposit IS NULL OR min_deposit > 0) AND
    (max_deposit IS NULL OR max_deposit > 0) AND
    (min_withdrawal IS NULL OR min_withdrawal > 0) AND
    (max_withdrawal IS NULL OR max_withdrawal > 0) AND
    (min_transfer IS NULL OR min_transfer > 0) AND
    (max_transfer IS NULL OR max_transfer > 0)
  ),
  CONSTRAINT min_max_deposit CHECK (min_deposit IS NULL OR max_deposit IS NULL OR min_deposit <= max_deposit),
  CONSTRAINT min_max_withdrawal CHECK (min_withdrawal IS NULL OR max_withdrawal IS NULL OR min_withdrawal <= max_withdrawal),
  CONSTRAINT min_max_transfer CHECK (min_transfer IS NULL OR max_transfer IS NULL OR min_transfer <= max_transfer),
  CONSTRAINT valid_dates_order CHECK (valid_to IS NULL OR valid_to > valid_from)
);

-- Indexes
CREATE INDEX idx_wl_wallet_id ON financial.wallet_limits(wallet_id) WHERE wallet_id IS NOT NULL;
CREATE INDEX idx_wl_wallet_type ON financial.wallet_limits(wallet_type) WHERE wallet_type IS NOT NULL;
CREATE INDEX idx_wl_subscription_plan ON financial.wallet_limits(subscription_plan) WHERE subscription_plan IS NOT NULL;
CREATE INDEX idx_wl_active ON financial.wallet_limits(active, priority DESC) WHERE active = true;
-- Index for currently valid limits (without time-based predicate for immutability)
CREATE INDEX idx_wl_valid_period ON financial.wallet_limits(valid_from, valid_to)
  WHERE active = true AND valid_to IS NULL;

-- Comments
COMMENT ON TABLE financial.wallet_limits IS 'Configurable transaction limits for wallets';
COMMENT ON COLUMN financial.wallet_limits.wallet_id IS 'Specific wallet (takes highest priority)';
COMMENT ON COLUMN financial.wallet_limits.wallet_type IS 'Limits for all wallets of this type';
COMMENT ON COLUMN financial.wallet_limits.subscription_plan IS 'Limits based on subscription plan';
COMMENT ON COLUMN financial.wallet_limits.priority IS 'Higher number = higher priority when multiple limits apply';
COMMENT ON COLUMN financial.wallet_limits.currency IS 'Currency for all limit amounts';
