-- Backfill: uzupelnienie personalizacji o pole message z payload_json (pozycje zamowien)
-- Dotyczy pozycji z pustym personalization i niepustym message w payload

UPDATE order_items
SET personalization = CONCAT('Wiadomość: ', TRIM(JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.message'))))
WHERE payload_json IS NOT NULL
  AND personalization IS NULL
  AND JSON_EXTRACT(payload_json, '$.message') IS NOT NULL
  AND JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.message')) != ''
  AND JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.message')) != 'null';

-- Backfill: import wiadomosci klienta z payload zamowienia do order_notes
-- Dotyczy zamowien z polem message w payload ale bez notatki typu 'message'

INSERT INTO order_notes (order_id, note_type, comment, created_at)
SELECT o.id, 'message', TRIM(JSON_UNQUOTE(JSON_EXTRACT(o.payload_json, '$.message'))), NOW()
FROM orders o
LEFT JOIN order_notes n ON n.order_id = o.id AND n.note_type = 'message'
WHERE o.payload_json IS NOT NULL
  AND JSON_EXTRACT(o.payload_json, '$.message') IS NOT NULL
  AND JSON_UNQUOTE(JSON_EXTRACT(o.payload_json, '$.message')) != ''
  AND JSON_UNQUOTE(JSON_EXTRACT(o.payload_json, '$.message')) != 'null'
  AND n.id IS NULL;
