-- Migration 0038: Sell Decision Engine schema (VS-10)
-- Creates tables for sell decision generation, validation, and approval tracking

CREATE TABLE IF NOT EXISTS model_operations.sell_decisions (
    id UUID PRIMARY KEY,
    model_id UUID NOT NULL REFERENCES model_operations.models(id),
    status VARCHAR(50) NOT NULL,
    pbo_score DECIMAL(5,4),
    dsr_metric DECIMAL(5,4),
    oos_performance JSONB,
    sell_priority INT,
    target_quantity INT,
    target_price DECIMAL(15,2),
    approval_id UUID REFERENCES model_operations.approval_proposals(id),
    execution_id UUID,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_by VARCHAR(255) NOT NULL,
    created_justification TEXT,
    published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    correlation_id UUID NOT NULL,
    revision INT NOT NULL DEFAULT 1
);

CREATE INDEX IF NOT EXISTS ix_sell_decisions_model_id ON model_operations.sell_decisions(model_id);
CREATE INDEX IF NOT EXISTS ix_sell_decisions_status ON model_operations.sell_decisions(status);
CREATE INDEX IF NOT EXISTS ix_sell_decisions_correlation_id ON model_operations.sell_decisions(correlation_id);
CREATE INDEX IF NOT EXISTS ix_sell_decisions_published_at ON model_operations.sell_decisions(published_at DESC);

CREATE TABLE IF NOT EXISTS model_operations.sell_decision_evidence (
    id UUID PRIMARY KEY,
    decision_id UUID NOT NULL REFERENCES model_operations.sell_decisions(id),
    evidence_type VARCHAR(50) NOT NULL,
    evidence_url TEXT NOT NULL,
    validated_at TIMESTAMPTZ,
    validator_email VARCHAR(255),
    comments TEXT,
    published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    correlation_id UUID NOT NULL
);

CREATE INDEX IF NOT EXISTS ix_sell_decision_evidence_decision_id ON model_operations.sell_decision_evidence(decision_id);
CREATE INDEX IF NOT EXISTS ix_sell_decision_evidence_type ON model_operations.sell_decision_evidence(evidence_type);
CREATE INDEX IF NOT EXISTS ix_sell_decision_evidence_correlation_id ON model_operations.sell_decision_evidence(correlation_id);
