-- Add deleted_at to helicopters so takeover and usage queries can safely filter active rows.

SET @schema_name := DATABASE();
SET @has_helicopters := (
  SELECT COUNT(*)
  FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = @schema_name
    AND TABLE_NAME = 'helicopters'
);

SET @has_deleted_at := (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @schema_name
    AND TABLE_NAME = 'helicopters'
    AND COLUMN_NAME = 'deleted_at'
);

SET @sql_add_deleted_at := IF(
  @has_helicopters > 0 AND @has_deleted_at = 0,
  'ALTER TABLE helicopters ADD COLUMN deleted_at DATETIME(6) NULL AFTER updated_at',
  'SELECT 1'
);
PREPARE stmt_add_deleted_at FROM @sql_add_deleted_at;
EXECUTE stmt_add_deleted_at;
DEALLOCATE PREPARE stmt_add_deleted_at;

SET @idx_deleted_at_exists := (
  SELECT COUNT(*)
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = @schema_name
    AND TABLE_NAME = 'helicopters'
    AND INDEX_NAME = 'idx_helicopters_deleted_at'
);

SET @sql_add_deleted_at_idx := IF(
  @has_helicopters > 0 AND @has_deleted_at > 0 AND @idx_deleted_at_exists = 0,
  'ALTER TABLE helicopters ADD INDEX idx_helicopters_deleted_at (deleted_at)',
  'SELECT 1'
);
PREPARE stmt_add_deleted_at_idx FROM @sql_add_deleted_at_idx;
EXECUTE stmt_add_deleted_at_idx;
DEALLOCATE PREPARE stmt_add_deleted_at_idx;
