-- Per-business API keys (OpenRouter for Amber and Sara, Google for the website check), stored encrypted in the database so each business
-- can have its own and a change takes effect straight away, with no environment edit and no restart.
-- The value is encrypted by the application (AES-GCM, same scheme as the agent secrets); the table never holds a plain key.
-- Idempotent: safe to re-run. Run it BEFORE deploying the build that uses it.

CREATE TABLE IF NOT EXISTS dim_tenant_api_key (
  id               BIGINT       NOT NULL AUTO_INCREMENT,
  tenant_id        INT          NOT NULL,
  key_code         VARCHAR(40)  NOT NULL,                 -- OPENROUTER or GOOGLE_ANALYSER
  secret_encrypted TEXT         NOT NULL,
  hint             VARCHAR(8)   NULL,                     -- last characters, so an admin can tell which key is saved
  updated_by       INT          NULL,
  created_at       DATETIME     NOT NULL,
  updated_at       DATETIME     NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_tenant_api_key (tenant_id, key_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
