-- Add canonical first/last name pair to user_profiles. The older
-- display_name column is kept as a derived/optional override (nicknames,
-- vanity formatting). Backfills first_name + last_name from display_name
-- by splitting on the first whitespace run; single-token names land as
-- (display_name, NULL) so we never throw away existing data.
ALTER TABLE "user_profiles"
  ADD COLUMN IF NOT EXISTS "first_name" text,
  ADD COLUMN IF NOT EXISTS "last_name" text;

-- Backfill: split display_name on the first run of whitespace.
-- - "Alice" → first_name='Alice', last_name=NULL
-- - "Alice Smith" → first_name='Alice', last_name='Smith'
-- - "Alice Mary Smith" → first_name='Alice', last_name='Mary Smith'
-- Skip rows that already have a first_name set so re-runs are no-ops.
UPDATE "user_profiles"
SET
  "first_name" = COALESCE(NULLIF(SPLIT_PART("display_name", ' ', 1), ''), "display_name"),
  "last_name" = NULLIF(
    REGEXP_REPLACE("display_name", '^\S+\s+', ''),
    "display_name"
  )
WHERE "first_name" IS NULL;
