-- Migration v74: Hardened Profile View Velocity Limiter
-- Prevents proxy swarm view-botting by adding a global velocity cap per profile across all IPs.

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_ip_count integer;
  profile_ip_count integer;
  profile_global_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;

  -- Tier 1: Max 60 view attempts per minute per IP across any profiles
  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 < 60
  returning request_count into global_ip_count;

  if global_ip_count is null then
    return false;
  end if;

  -- Tier 2: Max 10 view attempts per minute per IP on the SAME profile
  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 < 10
  returning request_count into profile_ip_count;

  if profile_ip_count is null then
    return false;
  end if;

  -- Tier 3: Global Profile Velocity Cap (Blocks rotating proxy swarms)
  -- No single profile may accumulate more than 30 views per minute across all IPs combined
  insert into public.profile_view_rate_limits(rate_key, bucket_started, request_count)
  values ('target_profile:' || 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 < 30
  returning request_count into profile_global_count;

  if profile_global_count is null then
    return false;
  end if;

  -- 1% sampling to clean up expired buckets older than 1 day
  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;
