-- D&G now uses recoverable email/password accounts. Keep the legacy function
-- names so existing auth.users triggers are upgraded in place.

create or replace function public.create_profile_for_allowlisted_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
  v_display_name text;
begin
  if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
    raise exception using
      errcode = '42501',
      message = 'A Dungeons & Ground account requires an email address.';
  end if;

  v_display_name := coalesce(
    nullif(btrim(new.raw_user_meta_data ->> 'display_name'), ''),
    split_part(new.email, '@', 1),
    'Adventurer'
  );

  insert into public.profiles(id, display_name)
  values (new.id, left(v_display_name, 80))
  on conflict (id) do update
    set display_name = excluded.display_name;

  return new;
end;
$$;

revoke all on function public.create_profile_for_allowlisted_user() from public, anon, authenticated;

create or replace function public.enforce_alpha_email_allowlist()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
    raise exception using
      errcode = '42501',
      message = 'A Dungeons & Ground account requires an email address.';
  end if;
  return new;
end;
$$;

revoke all on function public.enforce_alpha_email_allowlist() from public, anon, authenticated;

-- Installations may contain confirmed email users created before the D&G
-- schema. Give every non-anonymous email account a profile without touching
-- existing campaign ownership or display names.
insert into public.profiles(id, display_name)
select
  auth_user.id,
  left(coalesce(
    nullif(btrim(auth_user.raw_user_meta_data ->> 'display_name'), ''),
    split_part(auth_user.email, '@', 1),
    'Adventurer'
  ), 80)
from auth.users auth_user
where not coalesce(auth_user.is_anonymous, false)
  and nullif(btrim(auth_user.email), '') is not null
on conflict (id) do nothing;

create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
  select 8;
$$;

revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;

notify pgrst, 'reload schema';
