CREATE OR REPLACE FUNCTION notify_new_message()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify(
    'new_message',
    json_build_object(
      'id', NEW.id,
      'text', NEW.text,
      'senderId', NEW.senderId,
      'receiverId', NEW.receiverId,
      'createdAt', NEW.createdAt
    )::text
  );
  RETURN NEW;
END;
$$;

CREATE TRIGGER message_insert_trigger
AFTER INSERT ON messages
FOR EACH ROW EXECUTE FUNCTION notify_new_message();
