SET @lead_last_exported_column_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'leads'
      AND COLUMN_NAME = 'last_exported_at'
);

SET @ddl := IF(
    @lead_last_exported_column_exists = 0,
    'ALTER TABLE leads ADD COLUMN last_exported_at DATETIME NULL AFTER notes',
    'SELECT 1'
);

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

SET @lead_last_exported_index_exists := (
    SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'leads'
      AND INDEX_NAME = 'idx_leads_last_exported_at'
);

SET @ddl := IF(
    @lead_last_exported_index_exists = 0,
    'ALTER TABLE leads ADD INDEX idx_leads_last_exported_at (last_exported_at)',
    'SELECT 1'
);

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