-- Triggers for other tables to notify SSE channel

CREATE OR REPLACE FUNCTION notify_generic_change()
RETURNS trigger AS $$
DECLARE
  payload TEXT;
BEGIN
  payload := json_build_object(
    'table', TG_TABLE_NAME,
    'operation', TG_OP,
    'old', row_to_json(OLD),
    'new', row_to_json(NEW)
  )::text;
  PERFORM pg_notify('sse_events', payload);
  IF TG_OP = 'DELETE' THEN
    RETURN OLD;
  ELSE
    RETURN NEW;
  END IF;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS cliente_notify_trigger ON "Cliente";
CREATE TRIGGER cliente_notify_trigger
  AFTER INSERT OR UPDATE OR DELETE ON "Cliente"
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW
  EXECUTE PROCEDURE notify_generic_change();

DROP TRIGGER IF EXISTS tarea_notify_trigger ON "TareaRealizada";
CREATE TRIGGER tarea_notify_trigger
  AFTER INSERT OR UPDATE OR DELETE ON "TareaRealizada"
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW
  EXECUTE PROCEDURE notify_generic_change();

DROP TRIGGER IF EXISTS asistencia_notify_trigger ON "Asistencia";
CREATE TRIGGER asistencia_notify_trigger
  AFTER INSERT OR UPDATE OR DELETE ON "Asistencia"
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW
  EXECUTE PROCEDURE notify_generic_change();
