-- Phase 83: Separate pull status mappings table for Allegro
-- Pull direction (Allegro -> orderPRO) needs its own table with UNIQUE on allegro_status_code
-- because push direction has UNIQUE on orderpro_status_code (one Allegro status per orderPRO status)

CREATE TABLE IF NOT EXISTS allegro_order_status_pull_mappings (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    allegro_status_code VARCHAR(100) NOT NULL,
    allegro_status_name VARCHAR(255) DEFAULT NULL,
    orderpro_status_code VARCHAR(100) DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY allegro_pull_allegro_code_unique (allegro_status_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Pre-populate from existing push mappings (reverse: for each allegro_status_code take newest row)
INSERT IGNORE INTO allegro_order_status_pull_mappings (allegro_status_code, allegro_status_name, orderpro_status_code)
SELECT asm.allegro_status_code, asm.allegro_status_name, asm.orderpro_status_code
FROM allegro_order_status_mappings asm
INNER JOIN (
    SELECT allegro_status_code, MAX(id) AS max_id
    FROM allegro_order_status_mappings
    WHERE allegro_status_code IS NOT NULL
      AND allegro_status_code <> ''
    GROUP BY allegro_status_code
) latest ON asm.id = latest.max_id
WHERE asm.allegro_status_code IS NOT NULL
  AND asm.allegro_status_code <> '';
