-- Migration: Add delivery tracking columns to shipment_packages
-- Phase 27: Shipment Tracking Backend

-- Idempotent: skip if columns already exist
SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'shipment_packages' AND COLUMN_NAME = 'delivery_status');

SET @sql_add = IF(@col_exists = 0,
    'ALTER TABLE shipment_packages
        ADD COLUMN delivery_status VARCHAR(32) NOT NULL DEFAULT ''unknown'' AFTER status,
        ADD COLUMN delivery_status_raw VARCHAR(128) NULL AFTER delivery_status,
        ADD COLUMN delivery_status_updated_at DATETIME NULL AFTER delivery_status_raw',
    'SELECT 1');
PREPARE stmt FROM @sql_add;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Add index (idempotent)
SET @idx_exists = (SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'shipment_packages' AND INDEX_NAME = 'idx_delivery_status');

SET @sql_idx = IF(@idx_exists = 0,
    'ALTER TABLE shipment_packages ADD INDEX idx_delivery_status (delivery_status)',
    'SELECT 1');
PREPARE stmt FROM @sql_idx;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Set initial delivery_status for existing packages based on current status
-- label_ready = etykieta gotowa, NIE doręczona — ustawiamy confirmed (tracking cron zaktualizuje)
UPDATE shipment_packages SET delivery_status = 'confirmed' WHERE status = 'label_ready' AND delivery_status = 'unknown';
UPDATE shipment_packages SET delivery_status = 'created' WHERE status = 'created' AND provider != 'manual' AND delivery_status = 'unknown';
