-- Reserve / whitelist the "?" username.
-- Run in the Supabase SQL Editor to allow assigning the "?" handle to an account.

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 (
      id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid
      and username::text = '!'
    )
    or (
      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 = '$')
      or (new.id = '5092248b-24dc-4471-8dd4-ac916c15b215'::uuid and clean_username = '!')
      or (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;
$$;

create or replace function public.allow_profile_view_request(p_viewer_hash text, p_profile_username citext)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
  current_bucket timestamptz := date_trunc('minute', clock_timestamp());
  global_count integer;
  profile_count integer;
begin
  if p_viewer_hash is null or p_viewer_hash !~ '^[a-f0-9]{64}$'
    or p_profile_username is null
    or (
      p_profile_username::text !~ '^[a-z0-9_]{1,20}$'
      and p_profile_username::text not in ('$', '!', '?')
    ) then
    return false;
  end if;

  insert into public.profile_view_rate_limits(rate_key, bucket_started, request_count)
  values ('global:' || p_viewer_hash, current_bucket, 1)
  on conflict (rate_key, bucket_started) do update
    set request_count = profile_view_rate_limits.request_count + 1
    where profile_view_rate_limits.request_count < 120
  returning request_count into global_count;

  if global_count is null then
    return false;
  end if;

  insert into public.profile_view_rate_limits(rate_key, bucket_started, request_count)
  values ('profile:' || p_viewer_hash || ':' || p_profile_username::text, current_bucket, 1)
  on conflict (rate_key, bucket_started) do update
    set request_count = profile_view_rate_limits.request_count + 1
    where profile_view_rate_limits.request_count < 20
  returning request_count into profile_count;

  if profile_count is null then
    return false;
  end if;

  if random() < 0.01 then
    delete from public.profile_view_rate_limits
    where bucket_started < current_bucket - interval '1 day';
  end if;

  return true;
end;
$$;

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

-- Allow '?' in banned_usernames table check if present
do $$
begin
  if exists (
    select 1 from information_schema.tables
    where table_schema = 'public' and table_name = 'banned_usernames'
  ) then
    alter table public.banned_usernames drop constraint if exists banned_username_format;
    alter table public.banned_usernames add constraint banned_username_format check (
      (username::text) ~ '^[a-z0-9_]{1,20}$' or (username::text) in ('$', '!', '?')
    );
  end if;
end $$;
