-- Backfill clients.nationality_iso from the primary phone's parsed
-- value_country. Idempotent (only runs on rows where nationality_iso
-- is null), safe to re-execute. Phone country is a *proxy* for
-- nationality - the client-list UI labels the column "Country" rather
-- than "Nationality" to avoid implying it's authoritative (see §14.2).
--
-- Pattern: prefer the row marked `is_primary=true`; fall back to the
-- most recently created phone contact when no row is flagged primary.
WITH primary_phone AS (
  SELECT DISTINCT ON (cc.client_id)
    cc.client_id,
    cc.value_country
  FROM client_contacts cc
  WHERE cc.channel = 'phone'
    AND cc.value_country IS NOT NULL
  ORDER BY cc.client_id,
           cc.is_primary DESC,
           cc.created_at DESC
)
UPDATE clients c
SET nationality_iso = primary_phone.value_country
FROM primary_phone
WHERE c.nationality_iso IS NULL
  AND c.id = primary_phone.client_id;
