-- Migracja: dodanie pol unit pricing dla Google Merchant Center
-- Cel: obsluga unit_pricing_measure oraz unit_pricing_base_measure w adsPRO.
-- Idempotentnosc: kazdy ALTER i INDEX jest warunkowy przez INFORMATION_SCHEMA.

SET @sql = IF(
  EXISTS (
    SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'products'
      AND COLUMN_NAME = 'unit_pricing_measure'
  ),
  'DO 1',
  'ALTER TABLE `products` ADD COLUMN `unit_pricing_measure` VARCHAR(64) NULL DEFAULT NULL AFTER `custom_label_4`'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(
  EXISTS (
    SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'products'
      AND COLUMN_NAME = 'unit_pricing_base_measure'
  ),
  'DO 1',
  'ALTER TABLE `products` ADD COLUMN `unit_pricing_base_measure` VARCHAR(64) NULL DEFAULT NULL AFTER `unit_pricing_measure`'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(
  EXISTS (
    SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'products'
      AND COLUMN_NAME = 'unit_pricing_changed_at'
  ),
  'DO 1',
  'ALTER TABLE `products` ADD COLUMN `unit_pricing_changed_at` DATETIME NULL DEFAULT NULL AFTER `unit_pricing_base_measure`'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(
  EXISTS (
    SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'products'
      AND INDEX_NAME = 'idx_products_client_unit_pricing_measure'
  ),
  'DO 1',
  'ALTER TABLE `products` ADD INDEX `idx_products_client_unit_pricing_measure` (`client_id`, `unit_pricing_measure`)'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
