-- Reserve the "$" username for one existing account.
-- Run after v44-private-counts-leaderboard.sql.

alter table public.profiles
  drop constraint if exists username_ok;

alter table public.profiles
  add constraint username_ok check (
    (
      id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid
      and username::text = '$'
    )
    or (
      (username::text) ~ '^[a-z0-9_]{1,20}$'
      and lower(username::text) not in
        ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static')
    )
  );

create or replace function public.validate_profile_handles()
returns trigger
language plpgsql
as $$
declare
  clean_username text;
  clean_alias text;
begin
  clean_username := lower(coalesce(new.username::text, ''));
  clean_alias := nullif(lower(coalesce(new.alias::text, '')), '');

  new.username := clean_username::citext;
  new.alias := clean_alias::citext;

  if clean_username !~ '^[a-z0-9_]{1,20}$'
    and not (
      new.id = '6784f680-2a22-467b-9190-40c0b2eeb8a5'::uuid
      and clean_username = '$'
    ) then
    raise exception 'Invalid username';
  end if;

  if clean_username in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
    raise exception 'Reserved username';
  end if;

  if clean_alias is not null then
    if clean_alias !~ '^[a-z0-9_]{1,20}$' then
      raise exception 'Invalid alias';
    end if;

    if clean_alias = clean_username then
      raise exception 'Alias cannot be the same as username';
    end if;

    if clean_alias in ('login','signup','dashboard','api','admin','auth','about','terms','privacy','_next','static') then
      raise exception 'Reserved alias';
    end if;
  end if;

  if exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_username or lower(coalesce(p.alias::text,'')) = clean_username)
  ) then
    raise exception 'Username is already taken as a username or alias';
  end if;

  if clean_alias is not null and exists (
    select 1 from public.profiles p
    where p.id <> new.id
      and (lower(p.username::text) = clean_alias or lower(coalesce(p.alias::text,'')) = clean_alias)
  ) then
    raise exception 'Alias is already taken as a username or alias';
  end if;

  return new;
end;
$$;
