-- ============================================================================
-- Schema: trading
-- Table: bots
-- Description: Trading bots configurados por usuarios
-- Dependencies: auth.users, trading.bot_type, trading.bot_status, trading.timeframe
-- ============================================================================

CREATE TABLE trading.bots (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Propietario
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

  -- Configuración básica
  name VARCHAR(100) NOT NULL,
  bot_type trading.bot_type NOT NULL DEFAULT 'paper',
  status trading.bot_status NOT NULL DEFAULT 'paused',

  -- Símbolos a operar
  symbols VARCHAR(20)[] NOT NULL,
  timeframe trading.timeframe NOT NULL DEFAULT '1h',

  -- Capital
  initial_capital DECIMAL(20,8) NOT NULL,
  current_capital DECIMAL(20,8) NOT NULL,

  -- Risk management
  max_position_size_pct DECIMAL(5,2) DEFAULT 10.00, -- % del capital
  max_daily_loss_pct DECIMAL(5,2) DEFAULT 5.00,
  max_drawdown_pct DECIMAL(5,2) DEFAULT 20.00,

  -- Estrategia (referencia a ML signal provider)
  strategy_type VARCHAR(50),  -- 'atlas', 'orion', 'nova', 'custom'
  strategy_config JSONB DEFAULT '{}',

  -- Estadísticas
  total_trades INTEGER DEFAULT 0,
  winning_trades INTEGER DEFAULT 0,
  total_profit_loss DECIMAL(20,8) DEFAULT 0,
  win_rate DECIMAL(5,2) DEFAULT 0,

  -- Metadata
  started_at TIMESTAMPTZ,
  stopped_at TIMESTAMPTZ,
  last_trade_at TIMESTAMPTZ,

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

-- Índices
CREATE INDEX idx_bots_user ON trading.bots(user_id);
CREATE INDEX idx_bots_status ON trading.bots(status);
CREATE INDEX idx_bots_type ON trading.bots(bot_type);
CREATE INDEX idx_bots_user_status ON trading.bots(user_id, status);

-- Comentarios
COMMENT ON TABLE trading.bots IS 'Trading bots automatizados configurados por usuarios';
COMMENT ON COLUMN trading.bots.bot_type IS 'Tipo: paper (simulación), live (real), backtest';
COMMENT ON COLUMN trading.bots.strategy_type IS 'Estrategia ML: atlas, orion, nova, custom';
COMMENT ON COLUMN trading.bots.max_position_size_pct IS 'Máximo % del capital por posición';
COMMENT ON COLUMN trading.bots.max_daily_loss_pct IS 'Máxima pérdida diaria permitida (%)';
COMMENT ON COLUMN trading.bots.max_drawdown_pct IS 'Máximo drawdown permitido (%)';
