-- Add explicit service state to fleet statuses.

SET @has_status := (
  SELECT COUNT(*)
  FROM information_schema.columns
  WHERE table_schema = DATABASE()
    AND table_name = 'fleet_statuses'
    AND column_name = 'status'
);

SET @has_serviced_at := (
  SELECT COUNT(*)
  FROM information_schema.columns
  WHERE table_schema = DATABASE()
    AND table_name = 'fleet_statuses'
    AND column_name = 'serviced_at'
);

SET @sql1 := IF(
  @has_status = 0,
  'ALTER TABLE fleet_statuses ADD COLUMN status VARCHAR(16) NOT NULL DEFAULT ''active'' AFTER helicopter_id',
  'SELECT 1'
);
PREPARE stmt1 FROM @sql1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

SET @sql2 := IF(
  @has_serviced_at = 0,
  'ALTER TABLE fleet_statuses ADD COLUMN serviced_at DATETIME(3) NULL AFTER status',
  'SELECT 1'
);
PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;

SET @idx_status := (
  SELECT COUNT(*)
  FROM information_schema.statistics
  WHERE table_schema = DATABASE()
    AND table_name = 'fleet_statuses'
    AND index_name = 'idx_fleet_statuses_status'
);

SET @sql3 := IF(
  @idx_status = 0,
  'ALTER TABLE fleet_statuses ADD INDEX idx_fleet_statuses_status (status)',
  'SELECT 1'
);
PREPARE stmt3 FROM @sql3;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;

SET @idx_serviced := (
  SELECT COUNT(*)
  FROM information_schema.statistics
  WHERE table_schema = DATABASE()
    AND table_name = 'fleet_statuses'
    AND index_name = 'idx_fleet_statuses_serviced_at'
);

SET @sql4 := IF(
  @idx_serviced = 0,
  'ALTER TABLE fleet_statuses ADD INDEX idx_fleet_statuses_serviced_at (serviced_at)',
  'SELECT 1'
);
PREPARE stmt4 FROM @sql4;
EXECUTE stmt4;
DEALLOCATE PREPARE stmt4;
