-- v0.22.0: Provider health tracking + capability admin overrides.

-- ── Provider Health ─────────────────────────
-- Hourly bucketed health metrics per provider config.
-- In-memory accumulator flushes to this table every 60s.
-- Background job prunes rows older than 7 days.
CREATE TABLE IF NOT EXISTS provider_health (
    id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    provider_config_id  UUID NOT NULL REFERENCES provider_configs(id) ON DELETE CASCADE,
    window_start        TIMESTAMPTZ NOT NULL,  -- hourly bucket floor
    request_count       INT NOT NULL DEFAULT 0,
    error_count         INT NOT NULL DEFAULT 0,
    timeout_count       INT NOT NULL DEFAULT 0,
    total_latency_ms    BIGINT NOT NULL DEFAULT 0,   -- sum for avg calculation
    max_latency_ms      INT NOT NULL DEFAULT 0,
    last_error          TEXT,
    last_error_at       TIMESTAMPTZ,
    updated_at          TIMESTAMPTZ NOT NULL DEFAULT now(),

    UNIQUE (provider_config_id, window_start)
);

CREATE INDEX IF NOT EXISTS idx_provider_health_window
    ON provider_health (provider_config_id, window_start DESC);

-- ── Capability Overrides ────────────────────
-- Admin corrections for model capabilities.  Highest priority in the
-- three-tier resolution chain: catalog → heuristic → admin override.
CREATE TABLE IF NOT EXISTS capability_overrides (
    id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    provider_config_id  UUID REFERENCES provider_configs(id) ON DELETE CASCADE,
    model_id            TEXT NOT NULL,
    field               TEXT NOT NULL,   -- tool_calling, vision, thinking, reasoning, etc.
    value               TEXT NOT NULL,   -- "true"/"false" for bools, numeric string for ints
    set_by              UUID REFERENCES users(id) ON DELETE SET NULL,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),

    -- Unique per (provider, model, field).  NULL provider = applies to model globally.
    UNIQUE (provider_config_id, model_id, field)
);

CREATE INDEX IF NOT EXISTS idx_capability_overrides_model
    ON capability_overrides (model_id);
