-- v53: IP-based rate limiting for signup and public API endpoints.
-- All rate limit keys are hashed IP + endpoint strings, never raw IPs.

create table if not exists public.ip_rate_limits (
  key          text        primary key,
  window_start timestamptz not null default now(),
  count        integer     not null default 0
);

alter table public.ip_rate_limits enable row level security;
revoke all on table public.ip_rate_limits from public, anon, authenticated;
grant all on table public.ip_rate_limits to service_role;

create index if not exists ip_rate_limits_window_start_idx
  on public.ip_rate_limits (window_start);

-- Atomically checks and records a rate limit hit.
-- Returns true if the request is allowed, false if it should be rejected.
-- Uses FOR UPDATE to prevent race conditions. Runs probabilistic cleanup
-- (1% of calls) to keep the table from growing unboundedly.
create or replace function public.check_and_record_rate_limit(
  p_key            text,
  p_max            integer,
  p_window_seconds integer
)
returns boolean
language plpgsql
security definer
set search_path = public, pg_temp
as $$
declare
  v_row public.ip_rate_limits%rowtype;
begin
  -- Probabilistic cleanup: run on ~1% of calls so the table stays lean.
  if random() < 0.01 then
    delete from public.ip_rate_limits
    where window_start < now() - interval '1 day';
  end if;

  -- Lock existing row for this key.
  select * into v_row
  from public.ip_rate_limits
  where key = p_key
  for update;

  if not found then
    -- First request from this IP+endpoint combination.
    insert into public.ip_rate_limits (key, window_start, count)
    values (p_key, now(), 1)
    on conflict (key) do nothing;
    return true;
  end if;

  -- Window has expired — reset it.
  if v_row.window_start <= now() - make_interval(secs => p_window_seconds) then
    update public.ip_rate_limits
    set window_start = now(), count = 1
    where key = p_key;
    return true;
  end if;

  -- Over the limit for the current window.
  if v_row.count >= p_max then
    return false;
  end if;

  -- Within the limit — increment.
  update public.ip_rate_limits
  set count = count + 1
  where key = p_key;
  return true;
end;
$$;

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