-- create a trigger that calls the `send_fcm` edge function whenever a
-- new row is inserted into `notifications`.  This moves push logic entirely
-- to the backend, bypassing any CORS or auth issues that occur when web
-- clients try to invoke the function directly.

-- the http extension is available on Supabase databases; enable it if
-- it's not already installed.
create extension if not exists http;

create or replace function public.notifications_send_fcm_trigger()
returns trigger
language plpgsql as $$
declare
  _url text := 'https://pwbxgsuskvqwwaejxutj.supabase.co/functions/v1/send_fcm';
  _body text;
begin
  -- build a webhook-style payload that matches what the edge function
  -- expects when it's invoked from a database trigger.
  _body := json_build_object('record', row_to_json(NEW))::text;

  -- fire the POST; ignore the result since we don't want inserts to fail
  -- just because the push call returned an error.
  perform http_post(_url, _body, 'content-type=application/json');

  return NEW;
end;
$$;

-- drop any previous trigger (defensive) and create a new one.
drop trigger if exists trig_notifications_send_fcm on public.notifications;

create trigger trig_notifications_send_fcm
  after insert on public.notifications
  for each row
  execute function public.notifications_send_fcm_trigger();
