/*
  Warnings:

  - Made the column `username` on table `User` required. This step will fail if there are existing NULL values in that column.

*/
-- Backfill: assign a unique username derived from email or googleId for rows with NULL username
UPDATE "User"
SET "username" = lower(regexp_replace(split_part("email", '@', 1), '[^a-zA-Z0-9_]', '', 'g'))
WHERE "username" IS NULL;

-- Ensure uniqueness by appending a suffix for any collisions
UPDATE "User" u
SET "username" = u."username" || '_' || substr(u."id", 1, 6)
WHERE (
  SELECT COUNT(*) FROM "User" u2
  WHERE u2."username" = u."username" AND u2."id" != u."id"
) > 0;

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