-- Add optional username column, backfill, then constrain.
ALTER TABLE "User" ADD COLUMN "username" TEXT;

UPDATE "User"
SET "username" =
  LEFT(
    COALESCE(
      NULLIF(
        regexp_replace(
          lower(trim(split_part("email", '@', 1))),
          '[^a-z0-9_]',
          '_',
          'g'
        ),
        ''
      ),
      'supporter'
    ),
    23
  )
  || '_'
  || right(replace("id", '-', ''), 8);

ALTER TABLE "User" ALTER COLUMN "username" SET NOT NULL;

CREATE UNIQUE INDEX "User_username_key" ON "User" ("username");
