-- API Keys 管理
CREATE TABLE IF NOT EXISTS api_keys (
  id              TEXT PRIMARY KEY,
  skill_id        TEXT NOT NULL,
  name            TEXT NOT NULL DEFAULT 'default',
  key_hash        TEXT NOT NULL UNIQUE,
  key_prefix      TEXT NOT NULL,
  status          TEXT NOT NULL DEFAULT 'active',
  daily_limit     INTEGER NOT NULL DEFAULT 1000,
  created_at      INTEGER NOT NULL DEFAULT (strftime('%s','now')),
  created_by_email TEXT,
  created_by_phone TEXT,
  FOREIGN KEY (skill_id) REFERENCES skills(id)
);
CREATE INDEX IF NOT EXISTS idx_api_keys_skill ON api_keys(skill_id);
CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);

-- Skill 调用记录
CREATE TABLE IF NOT EXISTS skill_invocations (
  id              INTEGER PRIMARY KEY AUTOINCREMENT,
  ts              INTEGER NOT NULL DEFAULT (strftime('%s','now')),
  skill_id        TEXT NOT NULL,
  skill_name      TEXT,
  api_key_id      TEXT NOT NULL,
  caller_ip       TEXT,
  request_input   TEXT,
  response_output TEXT,
  response_status TEXT NOT NULL DEFAULT 'success',
  latency_ms      INTEGER,
  error_message   TEXT,
  FOREIGN KEY (skill_id) REFERENCES skills(id),
  FOREIGN KEY (api_key_id) REFERENCES api_keys(id)
);
CREATE INDEX IF NOT EXISTS idx_invocations_ts ON skill_invocations(ts DESC);
CREATE INDEX IF NOT EXISTS idx_invocations_skill ON skill_invocations(skill_id);
CREATE INDEX IF NOT EXISTS idx_invocations_key ON skill_invocations(api_key_id);
