-- =============================================================
-- COMPENSATING MIGRATION
-- Kompensuje: 20260302_000021_add_order_status_sync_direction_and_schedule.sql
-- Powód: Oryginalna migracja 000021 używa prostego ALTER TABLE (nie-idempotentna)
--        oraz seeduje shoppro_order_status_sync z interval=3600s z nadpisywaniem.
--        Migracja 000041 dodaje kolumnę order_status_sync_direction warunkowo przez
--        information_schema oraz koryguje interval na 900s z IFNULL (nie nadpisuje
--        istniejącego rekordu). Dotyczy środowisk niezgodnych z historią migracji.
-- Status: Środowisko zsynchronizowane po 2026-03-08. Migracja
--         idempotentna — bezpieczna do ponownego uruchomienia.
-- =============================================================
SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `integrations` ADD COLUMN `order_status_sync_direction` VARCHAR(32) NOT NULL DEFAULT ''shoppro_to_orderpro'' AFTER `orders_fetch_start_date`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'integrations'
      AND column_name = 'order_status_sync_direction'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

INSERT INTO cron_schedules (
    job_type, interval_seconds, priority, max_attempts, payload, enabled, last_run_at, next_run_at, created_at, updated_at
) VALUES (
    'shoppro_order_status_sync',
    900,
    100,
    3,
    NULL,
    1,
    NULL,
    NOW(),
    NOW(),
    NOW()
)
ON DUPLICATE KEY UPDATE
    interval_seconds = IFNULL(interval_seconds, VALUES(interval_seconds)),
    priority = IFNULL(priority, VALUES(priority)),
    max_attempts = IFNULL(max_attempts, VALUES(max_attempts)),
    updated_at = VALUES(updated_at);
