-- =====================================================
-- ML SCHEMA - BACKTEST RUNS TABLE
-- =====================================================
-- Description: Backtest execution history and results
-- Schema: ml
-- Author: ML Module Implementation
-- Date: 2026-01-18
-- =====================================================

-- Backtest status enum
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'backtest_status') THEN
    CREATE TYPE ml.backtest_status AS ENUM (
      'pending',
      'running',
      'completed',
      'failed',
      'cancelled'
    );
  END IF;
END$$;

CREATE TABLE IF NOT EXISTS ml.backtest_runs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- User who initiated the backtest (optional for system backtests)
  user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,

  -- Symbol and date range
  symbol VARCHAR(20) NOT NULL,
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,

  -- Status
  status ml.backtest_status NOT NULL DEFAULT 'pending',

  -- Configuration
  config JSONB NOT NULL,
  -- Example config:
  -- {
  --   "initialCapital": 10000,
  --   "riskPerTrade": 0.02,
  --   "rrConfig": "rr_2_1",
  --   "strategy": "ml_signals",
  --   "params": {}
  -- }

  -- Results (populated when completed)
  result JSONB,
  -- Example result:
  -- {
  --   "totalTrades": 150,
  --   "winRate": 0.52,
  --   "netProfit": 2500.00,
  --   "profitFactor": 1.45,
  --   "maxDrawdown": 0.15,
  --   "sharpeRatio": 1.8,
  --   "sortinoRatio": 2.1,
  --   "calmarRatio": 1.2,
  --   "expectancy": 0.05,
  --   "totalProfitR": 45.5,
  --   "trades": [...]
  -- }

  -- Error message (if failed)
  error TEXT,

  -- Timing
  started_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraints
  CONSTRAINT valid_date_range CHECK (end_date >= start_date),
  CONSTRAINT valid_config CHECK (jsonb_typeof(config) = 'object')
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_backtest_runs_user ON ml.backtest_runs(user_id);
CREATE INDEX IF NOT EXISTS idx_backtest_runs_symbol ON ml.backtest_runs(symbol);
CREATE INDEX IF NOT EXISTS idx_backtest_runs_status ON ml.backtest_runs(status);
CREATE INDEX IF NOT EXISTS idx_backtest_runs_created ON ml.backtest_runs(created_at DESC);

-- Index for finding completed backtests by profit
CREATE INDEX IF NOT EXISTS idx_backtest_runs_profit ON ml.backtest_runs((result->>'netProfit'))
  WHERE status = 'completed';

-- Composite index for user queries
CREATE INDEX IF NOT EXISTS idx_backtest_runs_user_symbol ON ml.backtest_runs(user_id, symbol, created_at DESC);

-- Comments
COMMENT ON TABLE ml.backtest_runs IS 'Backtest execution history and results';
COMMENT ON COLUMN ml.backtest_runs.user_id IS 'User who initiated the backtest (null for system backtests)';
COMMENT ON COLUMN ml.backtest_runs.symbol IS 'Trading symbol/pair tested';
COMMENT ON COLUMN ml.backtest_runs.config IS 'Backtest configuration (capital, risk, strategy, etc.)';
COMMENT ON COLUMN ml.backtest_runs.result IS 'Backtest results including metrics and trades';
COMMENT ON COLUMN ml.backtest_runs.error IS 'Error message if backtest failed';
COMMENT ON COLUMN ml.backtest_runs.started_at IS 'When backtest execution started';
COMMENT ON COLUMN ml.backtest_runs.completed_at IS 'When backtest finished (success or failure)';
