-- Phase 75: Separate pull status mappings table
-- Pull direction (shopPRO → orderPRO) needs its own table with UNIQUE on shoppro_status_code
-- because push direction allows many orderPRO statuses → one shopPRO status

CREATE TABLE IF NOT EXISTS order_status_pull_mappings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    integration_id INT NOT NULL,
    shoppro_status_code VARCHAR(100) NOT NULL,
    shoppro_status_name VARCHAR(255) DEFAULT NULL,
    orderpro_status_code VARCHAR(100) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE INDEX order_status_pull_mappings_integration_shoppro_unique (integration_id, shoppro_status_code),
    INDEX order_status_pull_mappings_integration_idx (integration_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Pre-populate from existing push mappings: for each (integration_id, shoppro_status_code)
-- take the row with the highest id (most recently created)
INSERT IGNORE INTO order_status_pull_mappings (integration_id, shoppro_status_code, shoppro_status_name, orderpro_status_code)
SELECT osm.integration_id, osm.shoppro_status_code, osm.shoppro_status_name, osm.orderpro_status_code
FROM order_status_mappings osm
INNER JOIN (
    SELECT integration_id, shoppro_status_code, MAX(id) AS max_id
    FROM order_status_mappings
    WHERE shoppro_status_code <> ''
    GROUP BY integration_id, shoppro_status_code
) latest ON osm.id = latest.max_id
WHERE osm.shoppro_status_code <> '';
