-- Phase 74: Reverse status mapping direction
-- Changes unique key from external_status_code to orderpro_status_code
-- so UI shows orderPRO statuses as rows with external status dropdown

-- ============================================================
-- 1. order_status_mappings (shopPRO)
-- ============================================================

-- Remove duplicates on (integration_id, orderpro_status_code) keeping newest row
DELETE osm1 FROM order_status_mappings osm1
INNER JOIN order_status_mappings osm2
ON osm1.integration_id = osm2.integration_id
   AND osm1.orderpro_status_code = osm2.orderpro_status_code
   AND osm1.id < osm2.id;

-- Drop old unique key on (integration_id, shoppro_status_code)
ALTER TABLE order_status_mappings
    DROP INDEX order_status_mappings_integration_shoppro_unique;

-- Add regular index on (integration_id, shoppro_status_code) for pull lookups
ALTER TABLE order_status_mappings
    ADD INDEX order_status_mappings_integration_shoppro_idx (integration_id, shoppro_status_code);

-- Drop old non-unique index on orderpro_status_code
ALTER TABLE order_status_mappings
    DROP INDEX order_status_mappings_orderpro_idx;

-- Add new unique key on (integration_id, orderpro_status_code)
ALTER TABLE order_status_mappings
    ADD UNIQUE INDEX order_status_mappings_integration_orderpro_unique (integration_id, orderpro_status_code);

-- ============================================================
-- 2. allegro_order_status_mappings (Allegro)
-- ============================================================

-- Remove duplicates on orderpro_status_code (non-NULL only) keeping newest row
DELETE asm1 FROM allegro_order_status_mappings asm1
INNER JOIN allegro_order_status_mappings asm2
ON asm1.orderpro_status_code = asm2.orderpro_status_code
   AND asm1.orderpro_status_code IS NOT NULL
   AND asm2.orderpro_status_code IS NOT NULL
   AND asm1.id < asm2.id;

-- Drop old unique key on allegro_status_code
ALTER TABLE allegro_order_status_mappings
    DROP INDEX allegro_order_status_mappings_code_unique;

-- Add regular index on allegro_status_code for pull lookups
ALTER TABLE allegro_order_status_mappings
    ADD INDEX allegro_order_status_mappings_allegro_code_idx (allegro_status_code);

-- Drop old non-unique index on orderpro_status_code
ALTER TABLE allegro_order_status_mappings
    DROP INDEX allegro_order_status_mappings_orderpro_code_idx;

-- Add new unique key on orderpro_status_code (NULLs allowed — multiple discovered-only rows OK)
ALTER TABLE allegro_order_status_mappings
    ADD UNIQUE INDEX allegro_order_status_mappings_orderpro_unique (orderpro_status_code);
