-- Migration 0002: Admission Testing & Model Candidates
-- Adds model_candidates table and supply_packages draft support

CREATE TABLE IF NOT EXISTS supply_intelligence_model_candidates (
    candidate_id TEXT PRIMARY KEY,
    account_id BIGINT NOT NULL,
    platform TEXT NOT NULL,
    model TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending_admission',
    source TEXT NOT NULL DEFAULT 'official_api',
    reason_code TEXT DEFAULT '',
    failure_summary TEXT DEFAULT '',
    discovered_at TIMESTAMPTZ NOT NULL,
    last_test_at TIMESTAMPTZ,
    updated_at TIMESTAMPTZ NOT NULL,
    version BIGINT NOT NULL DEFAULT 1,
    UNIQUE(platform, model)
);

CREATE INDEX idx_candidates_status ON supply_intelligence_model_candidates(status);
CREATE INDEX idx_candidates_platform ON supply_intelligence_model_candidates(platform);
CREATE INDEX idx_candidates_discovered ON supply_intelligence_model_candidates(discovered_at DESC);

CREATE SEQUENCE IF NOT EXISTS admission_test_id_seq;

CREATE TABLE IF NOT EXISTS supply_intelligence_admission_test_logs (
    test_id BIGINT PRIMARY KEY DEFAULT nextval('admission_test_id_seq'),
    candidate_id TEXT NOT NULL REFERENCES supply_intelligence_model_candidates(candidate_id),
    status TEXT NOT NULL,
    failure_code TEXT,
    failure_summary TEXT,
    tested_at TIMESTAMPTZ NOT NULL,
    version BIGINT NOT NULL DEFAULT 1
);

CREATE SEQUENCE IF NOT EXISTS supply_package_id_seq;

CREATE TABLE IF NOT EXISTS supply_intelligence_supply_packages (
    package_id BIGINT PRIMARY KEY DEFAULT nextval('supply_package_id_seq'),
    platform TEXT NOT NULL,
    model TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'draft',
    source TEXT NOT NULL DEFAULT 'si_auto',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    version BIGINT NOT NULL DEFAULT 1,
    UNIQUE(platform, model)
);

-- New fields to extend routing states (via migration, not replacement)
-- routing_states already has account_id as PK; add probe_execution_logs
CREATE SEQUENCE IF NOT EXISTS probe_log_id_seq;

CREATE TABLE IF NOT EXISTS supply_intelligence_probe_execution_logs (
    log_id BIGINT PRIMARY KEY DEFAULT nextval('probe_log_id_seq'),
    account_id BIGINT NOT NULL,
    platform TEXT NOT NULL,
    probe_result TEXT NOT NULL,
    failure_class TEXT,
    http_status INTEGER,
    latency_ms INTEGER,
    risk_score INTEGER NOT NULL,
    evaluated_transition TEXT NOT NULL,
    executed_at TIMESTAMPTZ NOT NULL,
    request_id TEXT NOT NULL,
    version BIGINT NOT NULL DEFAULT 1
);

CREATE INDEX idx_probe_logs_account_time ON supply_intelligence_probe_execution_logs(account_id, executed_at DESC);
