-- Create strategy_configs table for trading agent service
-- Manages strategy registration, configuration, and lifecycle

CREATE TABLE IF NOT EXISTS strategy_configs (
    strategy_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    strategy_name TEXT NOT NULL,
    strategy_type TEXT NOT NULL CHECK (strategy_type IN ('EqualWeight', 'RiskParity', 'MLOptimized', 'MeanVariance', 'Momentum', 'MeanReversion')),
    parameters JSONB NOT NULL DEFAULT '{}',
    status TEXT NOT NULL DEFAULT 'Active' CHECK (status IN ('Active', 'Paused', 'Stopped')),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(strategy_name)
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_strategy_configs_type ON strategy_configs(strategy_type);
CREATE INDEX IF NOT EXISTS idx_strategy_configs_status ON strategy_configs(status);
CREATE INDEX IF NOT EXISTS idx_strategy_configs_created ON strategy_configs(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_strategy_configs_parameters ON strategy_configs USING GIN (parameters);

-- Updated timestamp trigger
CREATE OR REPLACE FUNCTION update_strategy_configs_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_update_strategy_configs_updated_at
    BEFORE UPDATE ON strategy_configs
    FOR EACH ROW
    EXECUTE FUNCTION update_strategy_configs_updated_at();

-- Comments
COMMENT ON TABLE strategy_configs IS 'Strategy configuration and lifecycle management for trading agent';
COMMENT ON COLUMN strategy_configs.strategy_type IS 'Type of allocation strategy (EqualWeight, RiskParity, MLOptimized, MeanVariance, Momentum, MeanReversion)';
COMMENT ON COLUMN strategy_configs.parameters IS 'JSONB configuration parameters specific to strategy type';
COMMENT ON COLUMN strategy_configs.status IS 'Strategy status (Active, Paused, Stopped)';
