-- Store the latest online/offline state without persisting realtime coordinates.
SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'personnel_match' AND COLUMN_NAME = 'location_status') = 0,
  'ALTER TABLE `personnel_match` ADD COLUMN `location_status` varchar(32) NOT NULL DEFAULT ''OFFLINE'' COMMENT ''ONLINE/OFFLINE'' AFTER `match_type`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'personnel_match' AND COLUMN_NAME = 'finds_device_status') = 0,
  'ALTER TABLE `personnel_match` ADD COLUMN `finds_device_status` varchar(32) DEFAULT NULL COMMENT ''FindS device status'' AFTER `location_status`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'personnel_match' AND COLUMN_NAME = 'location_status_time') = 0,
  'ALTER TABLE `personnel_match` ADD COLUMN `location_status_time` datetime DEFAULT NULL COMMENT ''location status sync time'' AFTER `finds_device_status`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'personnel_match' AND INDEX_NAME = 'idx_personnel_match_location_status') = 0,
  'ALTER TABLE `personnel_match` ADD KEY `idx_personnel_match_location_status` (`location_status`, `match_status`)',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
