-- schema.sql
BEGIN;

CREATE TABLE schema_version (
    version_id      SERIAL PRIMARY KEY,
    applied_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    description     TEXT        NOT NULL
);

CREATE TABLE em_metrics (
    em_metric_id                 BIGSERIAL PRIMARY KEY,
    run_uuid                     UUID        NOT NULL,
    ci_pipeline                  VARCHAR(128) NOT NULL,
    job_name                     VARCHAR(128) NOT NULL,
    commit_hash                  CHAR(40)    NOT NULL,
    trace_version                SMALLINT    NOT NULL DEFAULT 1,
    captured_at                  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    peak_amplitude               NUMERIC(12,6) NOT NULL,
    median_bandpower             NUMERIC(12,6) NOT NULL,
    crosscorr_with_clockevents   NUMERIC(6,4)  NOT NULL,
    hf_outlier_flag              BOOLEAN     NOT NULL DEFAULT FALSE,
    spacer_config                VARCHAR(64),
    sampling_policy              VARCHAR(64),
    notes                        TEXT,
    CONSTRAINT em_metrics_peak_nonneg CHECK (peak_amplitude >= 0),
    CONSTRAINT em_metrics_band_nonneg CHECK (median_bandpower >= 0),
    CONSTRAINT em_metrics_corr_range CHECK (crosscorr_with_clockevents BETWEEN -1 AND 1),
    UNIQUE (run_uuid, job_name, trace_version)
);

CREATE INDEX idx_em_metrics_captured_at ON em_metrics (captured_at DESC);
CREATE INDEX idx_em_metrics_pipeline_job ON em_metrics (ci_pipeline, job_name);
CREATE INDEX idx_em_metrics_commit ON em_metrics (commit_hash);
CREATE INDEX idx_em_metrics_outlier ON em_metrics (hf_outlier_flag) WHERE hf_outlier_flag;

COMMIT;
