-- Steg 1: Ta bort beroenden som inte har ON DELETE CASCADE
-- RecipeIngredient -> Product saknar cascade och måste rensas manuellt först.
DELETE ri
FROM `RecipeIngredient` ri
JOIN `Product` p ON p.`id` = ri.`productId`
WHERE p.`ownerId` IS NULL;

-- Steg 2: Ta bort alla produkter utan ägare (globala seed-produkter)
-- Relaterade rader med ON DELETE CASCADE tas bort automatiskt
-- (InventoryItem, PantryItem, ReceiptAlias, ProductTag, Nutrition, UserProduct)
DELETE FROM `Product` WHERE `ownerId` IS NULL;

-- Steg 3: Uppdatera foreign key constraint (droppa befintlig först)
ALTER TABLE `Product`
  DROP FOREIGN KEY `Product_ownerId_fkey`;

-- Steg 4: Gör ownerId obligatoriskt
ALTER TABLE `Product`
  MODIFY COLUMN `ownerId` INT NOT NULL;

-- Steg 5: Lägg tillbaka owner-FK med ON DELETE CASCADE
ALTER TABLE `Product`
  ADD CONSTRAINT `Product_ownerId_fkey`
  FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`)
  ON DELETE CASCADE ON UPDATE CASCADE;
