-- One address, not two.
--
-- `Store.city` / `Store.state` are the operative fields: they decide CGST+SGST
-- versus IGST at checkout (checkout.service.ts) and resolve the courier zone
-- (shipping.service.ts). `store_branding.locality` / `.region` are what gets
-- published in the local listing.
--
-- They are the same fact, and merchants have been entering it on the SEO tab —
-- which wrote only to store_branding. Those shops read as "no address" on the
-- setup checklist and, worse, computed GST as though every order were
-- intra-state, because `Store.state` was NULL.
--
-- BrandingService now writes through on save. This backfills the shops that
-- were filled in before it did. Only fills where the store field is empty:
-- a store that already has a city keeps it, since that one was set deliberately.
--
-- Idempotent; safe to re-run.
BEGIN;

UPDATE store.stores s
SET
  city  = COALESCE(NULLIF(TRIM(s.city),  ''), NULLIF(TRIM(b.locality), '')),
  state = COALESCE(NULLIF(TRIM(s.state), ''), NULLIF(TRIM(b.region),   ''))
FROM store.store_branding b
WHERE b."storeId" = s.id
  AND (
    NULLIF(TRIM(COALESCE(s.city,  '')), '') IS NULL
    OR NULLIF(TRIM(COALESCE(s.state, '')), '') IS NULL
  );

COMMIT;
