SET @engine_column_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'lead_opportunities'
      AND COLUMN_NAME = 'engine'
);

SET @ddl := IF(
    @engine_column_exists = 0,
    'ALTER TABLE lead_opportunities ADD COLUMN engine VARCHAR(80) NULL AFTER source',
    'SELECT 1'
);

PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @engine_index_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'lead_opportunities'
      AND INDEX_NAME = 'idx_lead_opportunities_engine'
);

SET @ddl := IF(
    @engine_index_exists = 0,
    'ALTER TABLE lead_opportunities ADD INDEX idx_lead_opportunities_engine (engine)',
    'SELECT 1'
);

PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
