begin;

do $migration$
begin
  if to_regclass('identity.users') is not null
    and to_regclass('public.profiles') is not null then
    alter table public.profiles
      add column if not exists avatar_seed uuid not null default gen_random_uuid(),
      add column if not exists avatar_palette smallint not null
        default (floor(random() * 8)::smallint),
      add column if not exists avatar_renderer_version smallint not null default 1;

    alter table public.profiles
      drop constraint if exists profiles_avatar_palette_check,
      add constraint profiles_avatar_palette_check
        check (avatar_palette between 0 and 7),
      drop constraint if exists profiles_avatar_renderer_version_check,
      add constraint profiles_avatar_renderer_version_check
        check (avatar_renderer_version = 1);

    grant update (
      avatar_seed,
      avatar_palette,
      avatar_renderer_version
    ) on table public.profiles to authenticated;
  end if;
end
$migration$;

commit;
