-- Migration 013: Telemetria de uso geral (NAO cobra quota)
-- Cada operacao read/write no app gera um evento aqui.
-- Usado pra dashboard de uso + deteccao de fraude/reversa.

CREATE TABLE IF NOT EXISTS usage_events (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  device_id INT UNSIGNED NULL,
  company_id INT UNSIGNED NULL,
  user_id INT UNSIGNED NULL,
  tco_model VARCHAR(20) NOT NULL COMMENT 'BVDR2 / BVDR1 / MTCO1390 / unknown',
  tacho_serial VARCHAR(40) DEFAULT NULL COMMENT 'serial do tacografo conectado',
  operation VARCHAR(60) NOT NULL COMMENT 'detect, read_vin, write_odo, library_apply, workshop_login, kitas, etc',
  op_kind ENUM('read','write','detect','action') NOT NULL DEFAULT 'read',
  target VARCHAR(120) DEFAULT NULL COMMENT 'campo/DID alvo da op',
  success TINYINT(1) NOT NULL DEFAULT 1,
  error_msg VARCHAR(255) DEFAULT NULL,
  duration_ms INT UNSIGNED DEFAULT NULL,
  client_ts DATETIME NULL COMMENT 'timestamp do dispositivo (offline-safe)',
  server_ts DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_device_ts (device_id, server_ts),
  KEY idx_company_ts (company_id, server_ts),
  KEY idx_model_op (tco_model, operation),
  KEY idx_serial_ts (tacho_serial, server_ts),
  KEY idx_op_kind (op_kind, server_ts),
  KEY idx_server_ts (server_ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
