-- Per-provider rate limit configuration (admin-managed).
-- Controls how many requests per time window are allowed globally per provider.

CREATE TABLE admin_rate_limits (
    id                   UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    provider_name        VARCHAR(50)  NOT NULL UNIQUE REFERENCES admin_providers(provider_name) ON DELETE CASCADE,
    max_requests         INTEGER      NOT NULL DEFAULT 30,
    time_window_seconds  INTEGER      NOT NULL DEFAULT 60,
    updated_at           TIMESTAMPTZ  NOT NULL DEFAULT now()
);

-- Seed default rate limits for each provider
INSERT INTO admin_rate_limits (provider_name, max_requests, time_window_seconds) VALUES
    ('gemini',    29, 60),
    ('openai',    50, 60),
    ('anthropic', 40, 60);

-- Audit log for admin actions (provider changes, rate limit updates, role changes).
-- Provides traceability for all admin mutations.

CREATE TABLE audit_log (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    admin_user_id   UUID         REFERENCES users(id) ON DELETE SET NULL,
    action          VARCHAR(100) NOT NULL,
    target_type     VARCHAR(50),
    target_id       VARCHAR(255),
    details         JSONB,
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT now()
);

CREATE INDEX idx_audit_log_created_at ON audit_log(created_at DESC);
CREATE INDEX idx_audit_log_admin_user ON audit_log(admin_user_id);
