-- ─────────────────────────────────────────────────────────────────────────────
-- 055 — Put the tax invoice link in the "Order Delivered" email
--
-- The invoice is issued and linked on delivery (OrdersService.sendStatusEmail),
-- which passes an `invoiceUrl` variable. Without this the variable renders into
-- a template that never mentions it, and the customer gets no invoice at all.
--
-- Only the SYSTEM DEFAULT body is touched. A merchant who has customised their
-- own "Order Delivered" template keeps their copy untouched — that is the whole
-- point of copy-on-write (migration 052) — and will not get the link until they
-- add {{invoiceUrl}} themselves. Rewriting merchant overrides here would undo
-- edits they deliberately made.
--
-- The button is wrapped so an empty `invoiceUrl` degrades to a dead-looking but
-- harmless block rather than a link to nowhere; the service passes '' when the
-- invoice could not be issued, and the surrounding copy still reads correctly.
-- ─────────────────────────────────────────────────────────────────────────────

BEGIN;

UPDATE platform.template_types
   SET "defaultBodyHtml" = "defaultBodyHtml" ||
'<p style="margin:0 0 12px;color:#475569;font-size:16px;line-height:1.65;text-align:center;">Your tax invoice for this order is ready.</p>' ||
'<p style="margin:0 0 8px;text-align:center;"><a href="{{invoiceUrl}}" style="display:inline-block;padding:12px 28px;background:#4f46e5;color:#ffffff;font-size:15px;font-weight:600;text-decoration:none;border-radius:8px;">Download invoice (PDF)</a></p>' ||
'<p style="margin:0 0 18px;color:#94a3b8;font-size:13px;line-height:1.6;text-align:center;">This link works for 30 days. After that, sign in to your account to download it any time.</p>',

       description = 'Sent when an order is delivered. Variables: customerName, orderNumber, invoiceUrl',
       "updatedBy" = 'migration_055',
       "updatedOn" = now()
 WHERE code = 'order_delivered'
   -- Idempotent: re-running must not append the block twice.
   AND "defaultBodyHtml" NOT LIKE '%{{invoiceUrl}}%';

COMMIT;
