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();


CREATE OR REPLACE FUNCTION notify_countdown_update()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify(
    'countdown_update',
    json_build_object(
      'id', NEW.id,
      'relationshipId', NEW.relationship_id,
      'title', NEW.title,
      'date', NEW.date
    )::text
  );
  RETURN NEW;
END;
$$;

CREATE TRIGGER countdown_update_trigger
AFTER INSERT OR UPDATE ON countdowns
FOR EACH ROW EXECUTE FUNCTION notify_countdown_update();


CREATE OR REPLACE FUNCTION notify_relationship_status_change()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
    PERFORM pg_notify(
      'relationship_status_change',
      json_build_object(
        'id', NEW.id,
        'relationshipId', NEW.id,
        'status', NEW.is_accepted
      )::text
    );
  ELSIF (TG_OP = 'DELETE') THEN
    PERFORM pg_notify(
      'relationship_status_change',
      json_build_object(
        'id', OLD.id,
        'relationshipId', OLD.id,
        'status', 'deleted'
      )::text
    );
  END IF;
  RETURN NEW;
END;
$$;

CREATE TRIGGER relationship_status_change_trigger
AFTER INSERT OR UPDATE OR DELETE ON relationships
FOR EACH ROW EXECUTE FUNCTION notify_relationship_status_change();


CREATE OR REPLACE FUNCTION notify_profile_picture_update()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify(
    'profile_picture_update',
    json_build_object(
      'id', NEW.id,
      'userId', NEW.id,
      'pictureUrl', NEW.pfp_url
    )::text
  );
  RETURN NEW;
END;
$$;

CREATE TRIGGER profile_picture_update_trigger
AFTER UPDATE OF pfp_url ON users
FOR EACH ROW EXECUTE FUNCTION notify_profile_picture_update();
