-- Sprint 6: Immutable audit log table in ClickHouse.
-- Applied idempotently at startup via applyClickHouseDDL().
CREATE TABLE IF NOT EXISTS audit_logs (
    request_id        String,
    tenant_id         LowCardinality(String),
    user_id           String,
    timestamp         DateTime64(3, 'UTC'),
    model_requested   LowCardinality(String),
    model_used        LowCardinality(String),
    provider          LowCardinality(String),
    department        LowCardinality(String),
    user_role         LowCardinality(String),
    prompt_hash       FixedString(64),
    response_hash     FixedString(64),
    prompt_anonymized String,
    sensitivity_level LowCardinality(String),
    token_input       UInt32,
    token_output      UInt32,
    token_total       UInt32,
    cost_usd          Float64,
    latency_ms        UInt32,
    status            LowCardinality(String),
    error_type        LowCardinality(String),
    pii_entity_count  UInt16,
    stream            Bool
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (tenant_id, timestamp)
TTL timestamp + INTERVAL 90 DAY
SETTINGS index_granularity = 8192;
