CREATE TABLE IF NOT EXISTS gold.model_runs (
    model_run_id BIGSERIAL PRIMARY KEY,
    model_name TEXT NOT NULL,
    model_version TEXT NOT NULL,
    target_month TEXT NOT NULL CHECK (target_month ~ '^[0-9]{4}-[0-9]{2}$'),
    status TEXT NOT NULL,
    parameters JSONB NOT NULL DEFAULT '{}'::jsonb,
    started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    finished_at TIMESTAMPTZ,
    row_count INTEGER,
    error_message TEXT
);

ALTER TABLE gold.area_scores
    ADD COLUMN IF NOT EXISTS model_run_id BIGINT REFERENCES gold.model_runs(model_run_id);

CREATE INDEX IF NOT EXISTS idx_model_runs_target
    ON gold.model_runs(model_name, target_month, started_at DESC);
CREATE INDEX IF NOT EXISTS idx_area_scores_model_run
    ON gold.area_scores(model_run_id);
