-- Create enum for run status
DO $$ BEGIN
    CREATE TYPE run_status AS ENUM ('pending', 'running', 'completed', 'failed', 'cancelled', 'paused');
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

-- Update backtests table to remove status and error columns (these belong to runs)
ALTER TABLE backtests DROP COLUMN IF EXISTS status;
ALTER TABLE backtests DROP COLUMN IF EXISTS error;

-- Create runs table
CREATE TABLE IF NOT EXISTS runs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    backtest_id UUID NOT NULL REFERENCES backtests(id) ON DELETE CASCADE,
    run_number INTEGER NOT NULL,
    status run_status NOT NULL DEFAULT 'pending',
    speed_multiplier NUMERIC(10, 2) DEFAULT 1.0,
    error TEXT,
    started_at TIMESTAMP WITH TIME ZONE,
    completed_at TIMESTAMP WITH TIME ZONE,
    paused_at TIMESTAMP WITH TIME ZONE,
    progress NUMERIC(5, 2) DEFAULT 0, -- Progress percentage (0-100)
    current_simulation_date TIMESTAMP WITH TIME ZONE, -- Current simulation date
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    UNIQUE(backtest_id, run_number)
);

-- Move backtest_results to reference runs instead of backtests
ALTER TABLE backtest_results DROP CONSTRAINT IF EXISTS backtest_results_backtest_id_fkey;
ALTER TABLE backtest_results RENAME COLUMN backtest_id TO run_id;
ALTER TABLE backtest_results ADD CONSTRAINT backtest_results_run_id_fkey 
    FOREIGN KEY (run_id) REFERENCES runs(id) ON DELETE CASCADE;

-- Create indexes for better query performance
CREATE INDEX idx_runs_backtest_id ON runs(backtest_id);
CREATE INDEX idx_runs_status ON runs(status);
CREATE INDEX idx_runs_created_at ON runs(created_at DESC);

-- Create updated_at trigger for runs
DROP TRIGGER IF EXISTS update_runs_updated_at ON runs;
CREATE TRIGGER update_runs_updated_at BEFORE UPDATE
    ON runs FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Create a view for easy querying of latest run per backtest
CREATE OR REPLACE VIEW latest_runs AS
SELECT DISTINCT ON (backtest_id) 
    r.*,
    b.name as backtest_name,
    b.strategy,
    b.symbols,
    b.start_date,
    b.end_date,
    b.initial_capital
FROM runs r
JOIN backtests b ON b.id = r.backtest_id
ORDER BY backtest_id, created_at DESC;