-- Helper RPC to create a notification only if the user's settings allow it
-- Run this in Supabase SQL Editor with postgres role

create or replace function public.notify_if_allowed(
  _user_id uuid,
  _type text,
  _title text,
  _body text
) returns void language plpgsql security definer as $$
begin
  -- Check preferences
  if _type = 'chat' then
    if exists (select 1 from public.profiles p where p.id = _user_id and coalesce(p.notify_chat, true)) then
      insert into public.notifications(user_id, type, title, body) values (_user_id, _type, _title, _body);
    end if;
  elseif _type = 'event' then
    if exists (select 1 from public.profiles p where p.id = _user_id and coalesce(p.notify_events, true)) then
      insert into public.notifications(user_id, type, title, body) values (_user_id, _type, _title, _body);
    end if;
  elseif _type = 'forum' then
    if exists (select 1 from public.profiles p where p.id = _user_id and coalesce(p.notify_forum, true)) then
      insert into public.notifications(user_id, type, title, body) values (_user_id, _type, _title, _body);
    end if;
  elseif _type = 'payment' then
    if exists (select 1 from public.profiles p where p.id = _user_id and coalesce(p.notify_payments, false)) then
      insert into public.notifications(user_id, type, title, body) values (_user_id, _type, _title, _body);
    end if;
  else
    -- default: allow
    insert into public.notifications(user_id, type, title, body) values (_user_id, _type, _title, _body);
  end if;
end;$$;

-- Grant execute to authenticated users
revoke all on function public.notify_if_allowed(uuid, text, text, text) from public;
grant execute on function public.notify_if_allowed(uuid, text, text, text) to authenticated, anon;
