-- Harden public profile view tracking. Run after v38-admin-moderation.sql.

create table if not exists public.profile_view_rate_limits (
  rate_key text not null,
  bucket_started timestamptz not null,
  request_count integer not null default 0 check (request_count >= 0),
  primary key (rate_key, bucket_started)
);

alter table public.profile_view_rate_limits enable row level security;
revoke all on table public.profile_view_rate_limits from anon, authenticated;
grant all on table public.profile_view_rate_limits to service_role;

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}$' 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;

-- Close both old and current public increment paths.
revoke all on function public.increment_views(citext) from public, anon, authenticated;
revoke all on function public.increment_view_once(citext, text) from public, anon, authenticated;
grant execute on function public.increment_view_once(citext, text) to service_role;