CREATE TABLE IF NOT EXISTS gateway.content_policies (
    id uuid PRIMARY KEY,
    name text NOT NULL UNIQUE,
    description text NOT NULL DEFAULT '',
    action text NOT NULL CHECK (action IN ('audit', 'block', 'redact')),
    priority integer NOT NULL DEFAULT 0,
    paths text[] NOT NULL DEFAULT '{}',
    models text[] NOT NULL DEFAULT '{}',
    api_key_ids uuid[] NOT NULL DEFAULT '{}',
    rules jsonb NOT NULL DEFAULT '[]'::jsonb,
    enabled boolean NOT NULL DEFAULT true,
    revision bigint NOT NULL DEFAULT 1,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    CHECK (jsonb_typeof(rules) = 'array')
);

CREATE INDEX IF NOT EXISTS content_policies_runtime_idx
    ON gateway.content_policies (enabled, priority DESC, name);

COMMENT ON TABLE gateway.content_policies IS
    'Ordered request content policies compiled with Go RE2; only textual prompt fields are inspected or redacted.';

INSERT INTO gateway.content_policies
    (id, name, description, action, priority, rules, enabled)
VALUES
    ('00000000-0000-4000-8000-000000000016', '默认敏感信息脱敏',
     '对提示词文本中的常见 API 密钥、访问令牌、密码和 secret 赋值执行脱敏。',
     'redact', 1000,
     '[{"name":"OpenAI 风格密钥","pattern":"sk-[A-Za-z0-9_-]{16,}","replacement":"[REDACTED_API_KEY]"},{"name":"凭据赋值","pattern":"(?i)(api[_-]?key|access[_-]?token|password|secret)[[:space:]]*[:=][[:space:]]*[\"'']?([A-Za-z0-9_./+=-]{6,})","replacement":"$1=[REDACTED]"}]'::jsonb,
     true)
ON CONFLICT (id) DO NOTHING;

CREATE TABLE IF NOT EXISTS gateway.model_prices (
    id uuid PRIMARY KEY,
    provider_code text NOT NULL,
    model_pattern text NOT NULL,
    input_microunits_per_million bigint NOT NULL CHECK (input_microunits_per_million >= 0),
    output_microunits_per_million bigint NOT NULL CHECK (output_microunits_per_million >= 0),
    currency char(3) NOT NULL DEFAULT 'USD' CHECK (currency = upper(currency)),
    effective_from timestamptz NOT NULL,
    effective_to timestamptz,
    enabled boolean NOT NULL DEFAULT true,
    revision bigint NOT NULL DEFAULT 1,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    CHECK (effective_to IS NULL OR effective_to > effective_from),
    UNIQUE (provider_code, model_pattern, effective_from)
);

CREATE INDEX IF NOT EXISTS model_prices_runtime_idx
    ON gateway.model_prices (provider_code, enabled, effective_from DESC);

ALTER TABLE gateway.usage_daily
    ADD COLUMN IF NOT EXISTS cost_microunits bigint NOT NULL DEFAULT 0 CHECK (cost_microunits >= 0);

COMMENT ON COLUMN gateway.audit_events.cost_microunits IS
    'Estimated request cost in one-millionth currency units using the price version effective at request time.';
