-- Ensure Allergi mejeri uses "Laktosfri mjölk" as L3 node.

-- 1) Rename old node when no target node exists yet.
UPDATE `Category` c_old
JOIN `Category` c2
  ON c_old.parentId = c2.id
  AND c2.name = 'Allergi mejeri'
JOIN `Category` c1
  ON c2.parentId = c1.id
  AND c1.name = 'Mejeri, ost & ägg'
  AND c1.parentId IS NULL
LEFT JOIN `Category` c_new
  ON c_new.parentId = c2.id
  AND c_new.name = 'Laktosfri mjölk'
SET c_old.name = 'Laktosfri mjölk'
WHERE c_old.name = 'Mjölk'
  AND c_new.id IS NULL;

-- 2) Re-point product links from old node to new node if both exist.
UPDATE `Product` p
JOIN `Category` c_old
  ON p.categoryId = c_old.id
  AND c_old.name = 'Mjölk'
JOIN `Category` c2
  ON c_old.parentId = c2.id
  AND c2.name = 'Allergi mejeri'
JOIN `Category` c1
  ON c2.parentId = c1.id
  AND c1.name = 'Mejeri, ost & ägg'
  AND c1.parentId IS NULL
JOIN `Category` c_new
  ON c_new.parentId = c2.id
  AND c_new.name = 'Laktosfri mjölk'
SET p.categoryId = c_new.id;

-- 3) Remove duplicate old node when both old and new exist.
DELETE c_old
FROM `Category` c_old
JOIN `Category` c2
  ON c_old.parentId = c2.id
  AND c2.name = 'Allergi mejeri'
JOIN `Category` c1
  ON c2.parentId = c1.id
  AND c1.name = 'Mejeri, ost & ägg'
  AND c1.parentId IS NULL
JOIN `Category` c_new
  ON c_new.parentId = c2.id
  AND c_new.name = 'Laktosfri mjölk'
WHERE c_old.name = 'Mjölk';

-- 4) Create missing target node if needed.
INSERT INTO `Category` (`name`, `parentId`)
SELECT 'Laktosfri mjölk', c2.id
FROM `Category` c1
JOIN `Category` c2
  ON c2.parentId = c1.id
  AND c2.name = 'Allergi mejeri'
LEFT JOIN `Category` c3
  ON c3.parentId = c2.id
  AND c3.name = 'Laktosfri mjölk'
WHERE c1.name = 'Mejeri, ost & ägg'
  AND c1.parentId IS NULL
  AND c3.id IS NULL;
