-- =============================================================
-- COMPENSATING MIGRATION
-- Kompensuje: 20260302_000017_add_shoppro_orders_fetch_settings_to_integrations.sql
-- Powód: Oryginalna migracja 000017 używa prostego ALTER TABLE bez sprawdzenia
--        istnienia kolumn (nie-idempotentna). Na środowisku, gdzie kolumny
--        orders_fetch_enabled i orders_fetch_start_date już istniały (ręczne zmiany
--        lub wcześniejszy deploy), migracja 000017 zawodziła z błędem duplicate column.
--        Migracja 000039 dodaje kolumny warunkowo przez information_schema.
-- Status: Środowisko zsynchronizowane po 2026-03-08. Migracja
--         idempotentna — bezpieczna do ponownego uruchomienia.
-- =============================================================
SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `integrations` ADD COLUMN `orders_fetch_enabled` TINYINT(1) NOT NULL DEFAULT 0 AFTER `is_active`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'integrations'
      AND column_name = 'orders_fetch_enabled'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `integrations` ADD COLUMN `orders_fetch_start_date` DATE NULL AFTER `orders_fetch_enabled`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'integrations'
      AND column_name = 'orders_fetch_start_date'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
