CREATE TABLE IF NOT EXISTS law_firm_kommo_settings (
  id CHAR(36) NOT NULL,
  law_firm_id CHAR(36) NOT NULL,
  subdomain VARCHAR(120) NULL,
  encrypted_access_token VARBINARY(4096) NULL COMMENT 'Ciphertext only; never plaintext',
  access_token_last4 CHAR(4) NULL,
  encrypted_webhook_secret VARBINARY(4096) NULL COMMENT 'Ciphertext only; never plaintext',
  webhook_secret_last4 CHAR(4) NULL,
  encrypted_integration_secret_key VARBINARY(4096) NULL COMMENT 'Ciphertext only; never plaintext',
  integration_secret_key_last4 CHAR(4) NULL,
  encryption_key_version VARCHAR(50) NOT NULL DEFAULT 'v1',
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_by_user_id CHAR(36) NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_kommo_settings_law_firm (law_firm_id),
  KEY idx_kommo_settings_law_firm (law_firm_id, is_active),
  CONSTRAINT fk_kommo_settings_law_firm
    FOREIGN KEY (law_firm_id) REFERENCES law_firms (id),
  CONSTRAINT fk_kommo_settings_created_by
    FOREIGN KEY (created_by_user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
