CREATE TABLE IF NOT EXISTS audit.raw_artifacts (
    artifact_id BIGSERIAL PRIMARY KEY,
    run_id BIGINT REFERENCES audit.ingestion_runs(run_id),
    source_id BIGINT REFERENCES audit.data_sources(source_id),
    original_filename TEXT NOT NULL,
    raw_uri TEXT NOT NULL,
    sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
    size_bytes BIGINT NOT NULL CHECK (size_bytes >= 0),
    mime_type TEXT,
    uploaded_by TEXT NOT NULL DEFAULT 'system',
    notes TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (sha256)
);

ALTER TABLE audit.ingestion_runs
    ADD COLUMN IF NOT EXISTS raw_artifact_id BIGINT REFERENCES audit.raw_artifacts(artifact_id);

CREATE INDEX IF NOT EXISTS idx_raw_artifacts_run_id
    ON audit.raw_artifacts(run_id);
CREATE INDEX IF NOT EXISTS idx_raw_artifacts_source_id
    ON audit.raw_artifacts(source_id);
CREATE INDEX IF NOT EXISTS idx_raw_artifacts_created_at
    ON audit.raw_artifacts(created_at DESC);
