-- Migration 000011: Provider configurations stored in database
-- Replaces environment-variable-only provider config with DB-driven CRUD.
-- API keys are stored encrypted (AES-256-GCM via crypto.Encryptor).

CREATE TABLE provider_configs (
    id             UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id      TEXT        NOT NULL,
    provider       TEXT        NOT NULL
                               CHECK (provider IN ('openai','anthropic','azure','mistral','ollama')),
    display_name   TEXT        NOT NULL DEFAULT '',
    api_key_enc    TEXT        NOT NULL DEFAULT '',   -- AES-256-GCM encrypted, empty for Ollama
    base_url       TEXT        NOT NULL DEFAULT '',
    resource_name  TEXT        NOT NULL DEFAULT '',   -- Azure only
    deployment_id  TEXT        NOT NULL DEFAULT '',   -- Azure only
    api_version    TEXT        NOT NULL DEFAULT '2024-02-01',
    timeout_sec    INT         NOT NULL DEFAULT 30,
    max_conns      INT         NOT NULL DEFAULT 100,
    model_patterns TEXT[]      NOT NULL DEFAULT '{}', -- extra model name prefixes routed here
    is_active      BOOLEAN     NOT NULL DEFAULT TRUE,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_id, provider)
);

CREATE INDEX idx_provider_configs_tenant ON provider_configs(tenant_id, is_active);

CREATE TRIGGER provider_configs_updated_at
    BEFORE UPDATE ON provider_configs
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();
