USE `test_db`;

-- 1) Normalize usernames to avoid case/space variants.
UPDATE `users`
SET `username` = LOWER(TRIM(`username`))
WHERE `username` IS NOT NULL;

-- 2) Keep the lowest id for each username and delete duplicates.
DELETE u1
FROM `users` u1
INNER JOIN `users` u2
    ON u1.`username` = u2.`username`
    AND u1.`id` > u2.`id`;

-- 3) Enforce unique usernames at database level.
ALTER TABLE `users`
ADD CONSTRAINT `uq_users_username` UNIQUE (`username`);
