-- Supplemental vehicle master data. Gateway-owned VIN/plate/OEM identity remains authoritative.
CREATE TABLE IF NOT EXISTS vehicle_profile (
  vin VARCHAR(32) NOT NULL PRIMARY KEY,
  model_name VARCHAR(128) NOT NULL DEFAULT '',
  vehicle_type VARCHAR(64) NOT NULL DEFAULT '',
  company_name VARCHAR(128) NOT NULL DEFAULT '',
  operation_status VARCHAR(32) NOT NULL DEFAULT 'unknown',
  access_provider VARCHAR(128) NOT NULL DEFAULT '',
  first_access_at DATETIME(3) NULL,
  runtime_seconds BIGINT UNSIGNED NULL,
  source_system VARCHAR(64) NOT NULL DEFAULT 'manual',
  source_version VARCHAR(128) NOT NULL DEFAULT '',
  synced_at DATETIME(3) NULL,
  version INT NOT NULL DEFAULT 1,
  updated_by VARCHAR(128) NOT NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY idx_vehicle_profile_company (company_name),
  KEY idx_vehicle_profile_model (model_name),
  KEY idx_vehicle_profile_status (operation_status),
  KEY idx_vehicle_profile_provider (access_provider)
);

CREATE TABLE IF NOT EXISTS vehicle_profile_audit (
  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  vin VARCHAR(32) NOT NULL,
  profile_version INT NOT NULL,
  actor VARCHAR(128) NOT NULL,
  action VARCHAR(32) NOT NULL,
  snapshot_json LONGTEXT NOT NULL,
  changed_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  UNIQUE KEY uk_vehicle_profile_audit_version (vin, profile_version),
  KEY idx_vehicle_profile_audit_changed (changed_at)
);
