CREATE TABLE IF NOT EXISTS user_key_audit_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    event_id TEXT UNIQUE NOT NULL,
    actor_subject_id TEXT NOT NULL,
    actor_role TEXT NOT NULL CHECK (actor_role IN ('admin','user','system')),
    target_key_id TEXT NOT NULL,
    action TEXT NOT NULL CHECK (action IN ('create','reset','pause','resume','delete')),
    result TEXT NOT NULL CHECK (result IN ('success','denied','failed')),
    reason TEXT NOT NULL DEFAULT '',
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);

CREATE INDEX IF NOT EXISTS idx_user_key_audit_target_key_id ON user_key_audit_events(target_key_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_user_key_audit_actor_subject_id ON user_key_audit_events(actor_subject_id, created_at DESC);

CREATE TABLE IF NOT EXISTS subject_rate_limits (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject_id TEXT NOT NULL,
    action TEXT NOT NULL,
    window_start TEXT NOT NULL,
    hit_count INTEGER NOT NULL DEFAULT 0,
    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
    UNIQUE(subject_id, action, window_start)
);

CREATE INDEX IF NOT EXISTS idx_subject_rate_limits_lookup ON subject_rate_limits(subject_id, action, window_start);
