-- Dodaj kolumnę jeśli nie istnieje
SET @col_exists = (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'orders'
      AND COLUMN_NAME = 'last_status_checked_at'
);
SET @sql = IF(@col_exists = 0,
    'ALTER TABLE orders ADD COLUMN last_status_checked_at DATETIME NULL DEFAULT NULL COMMENT ''Timestamp ostatniego sprawdzenia statusu przez AllegroStatusSyncService'' AFTER source_updated_at',
    'SELECT ''Column last_status_checked_at already exists, skipping.'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Indeks kompozytowy wspiera zapytanie filtrujące po source + sortujące po source_updated_at
SET @idx_exists = (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'orders'
      AND INDEX_NAME = 'orders_source_updated_idx'
);
SET @sql = IF(@idx_exists = 0,
    'ALTER TABLE orders ADD INDEX orders_source_updated_idx (source, source_updated_at)',
    'SELECT ''Index orders_source_updated_idx already exists, skipping.'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
