begin;

alter table if exists public.ak_users
  drop constraint if exists ak_users_preferred_language_fkey;

alter table if exists public.ak_users
  add constraint ak_users_preferred_language_fkey
  foreign key (preferred_language)
  references public.ak_languages (id)
  on update cascade
  on delete set null;

create index if not exists idx_ak_users_preferred_language
  on public.ak_users (preferred_language);

alter table if exists public.ak_languages enable row level security;

do $$
begin
  if exists (
    select 1
    from pg_class c
    join pg_namespace n on n.oid = c.relnamespace
    where n.nspname = 'public'
      and c.relname = 'ak_languages'
      and c.relkind = 'r'
  ) and not exists (
    select 1
    from pg_policies
    where schemaname = 'public'
      and tablename = 'ak_languages'
      and policyname = 'ak_languages_active_select'
  ) then
    create policy ak_languages_active_select
      on public.ak_languages
      for select
      using (is_active = true);
  end if;
end
$$;

commit;
