-- Migracja: tabela cron_sync_status zamiast JSON w settings
-- Data: 2026-02-19
-- Opis: dedykowana tabela do sledzenia postepu pipeline CRON (kampanie, produkty)

CREATE TABLE IF NOT EXISTS `cron_sync_status` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `client_id` INT NOT NULL,
  `pipeline` ENUM('campaigns','products') NOT NULL,
  `sync_date` DATE NOT NULL,
  `phase` ENUM('pending','fetch','aggregate_30','aggregate_temp','done') NOT NULL DEFAULT 'pending',
  `started_at` DATETIME NULL,
  `completed_at` DATETIME NULL,
  `error_message` TEXT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY `uq_client_pipeline_date` (`client_id`, `pipeline`, `sync_date`),
  KEY `idx_pipeline_phase` (`pipeline`, `phase`),
  KEY `idx_client_id` (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Usuniecie kolumny force_sync_campaigns z clients
SET @sql = IF(
  EXISTS (
    SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'clients'
      AND COLUMN_NAME = 'force_sync_campaigns'
  ),
  'ALTER TABLE `clients` DROP COLUMN `force_sync_campaigns`',
  'DO 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Usuniecie kolumny force_sync_products z clients
SET @sql = IF(
  EXISTS (
    SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'clients'
      AND COLUMN_NAME = 'force_sync_products'
  ),
  'ALTER TABLE `clients` DROP COLUMN `force_sync_products`',
  'DO 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Usuniecie starych kluczy JSON z settings
DELETE FROM `settings` WHERE `setting_key` IN (
  'cron_campaigns_window_state',
  'cron_campaigns_state',
  'cron_products_pipeline_state'
);
