-- ==========================================
-- Chat Switchboard — 014 Audit & Usage
-- ==========================================
-- Audit trail and usage/cost tracking.
-- ICD §16 (Platform Administration), §17 (Export & Utility)
-- ==========================================

-- =========================================
-- AUDIT LOG
-- =========================================

CREATE TABLE IF NOT EXISTS audit_log (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    actor_id        UUID REFERENCES users(id) ON DELETE SET NULL,
    action          VARCHAR(100) NOT NULL,
    resource_type   VARCHAR(50) NOT NULL,
    resource_id     VARCHAR(255),
    metadata        JSONB DEFAULT '{}'::jsonb,
    ip_address      VARCHAR(45),
    user_agent      TEXT DEFAULT '',
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_actor ON audit_log(actor_id) WHERE actor_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_audit_log_resource ON audit_log(resource_type, resource_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);

COMMENT ON TABLE audit_log IS 'Immutable audit trail of all mutating operations';


-- =========================================
-- USAGE LOG
-- =========================================

CREATE TABLE IF NOT EXISTS usage_log (
    id                    UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    channel_id            UUID REFERENCES channels(id) ON DELETE SET NULL,
    user_id               UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    provider_config_id    UUID REFERENCES provider_configs(id) ON DELETE SET NULL,
    provider_scope        TEXT NOT NULL DEFAULT 'global',
    model_id              TEXT NOT NULL,
    role                  TEXT,
    prompt_tokens         INT NOT NULL DEFAULT 0,
    completion_tokens     INT NOT NULL DEFAULT 0,
    cache_creation_tokens INT NOT NULL DEFAULT 0,
    cache_read_tokens     INT NOT NULL DEFAULT 0,
    cost_input            NUMERIC(12,6),
    cost_output           NUMERIC(12,6),
    routing_decision      JSONB,
    created_at            TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_usage_log_user     ON usage_log(user_id);
CREATE INDEX IF NOT EXISTS idx_usage_log_created  ON usage_log(created_at);
CREATE INDEX IF NOT EXISTS idx_usage_log_provider ON usage_log(provider_config_id);
CREATE INDEX IF NOT EXISTS idx_usage_log_model    ON usage_log(model_id);
CREATE INDEX IF NOT EXISTS idx_usage_log_scope    ON usage_log(provider_scope);
