-- Dispara notificaciones push llamando a la Edge Function enviar-push (via pg_net) cuando:
--   INSERT de pedido            -> nuevo_pedido (avisa al dueno)
--   estado -> listo (delivery, sin asignar) -> listo_pool (avisa a repartidores disponibles)
--   se asigna repartidor (no auto-tomado)   -> asignado (avisa a ese repartidor)
-- El secreto para autenticar la llamada se lee de Vault (no queda en git).
create or replace function public.tg_notificar_push()
returns trigger
language plpgsql
security definer
set search_path to 'public'
as $$
declare
  v_evento text;
  v_secret text;
  v_url text := 'https://szzhhlevtrcambcoytiz.supabase.co/functions/v1/enviar-push';
  -- (la apikey se leia aqui escrita a mano; desde la migration
  --  20260719100000_push_anon_desde_vault.sql se lee de Vault)
  v_anon text := ''; begin
  if TG_OP = 'INSERT' then
    v_evento := 'nuevo_pedido';
  elsif TG_OP = 'UPDATE' then
    if new.tipo_entrega = 'delivery' and new.estado = 'listo' and new.repartidor_id is null
       and old.estado is distinct from 'listo' then
      v_evento := 'listo_pool';
    elsif new.repartidor_id is not null and old.repartidor_id is null and new.estado <> 'en_camino' then
      v_evento := 'asignado';
    end if;
  end if;

  if v_evento is null then return null; end if;

  select decrypted_secret into v_secret from vault.decrypted_secrets where name = 'push_secret' limit 1;

  perform net.http_post(
    url := v_url,
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'apikey', v_anon,
      'x-push-secret', coalesce(v_secret, '')
    ),
    body := jsonb_build_object('pedido_id', new.id, 'evento', v_evento)
  );
  return null;
end;
$$;

drop trigger if exists trg_notificar_push on public.pedidos;
create trigger trg_notificar_push
after insert or update on public.pedidos
for each row execute function public.tg_notificar_push();
