// import second from 'first'
import { removeReplyingMessage } from "../../app/slices/message";
import { useSendChannelMsgMutation } from "../../app/services/channel";
import { useSendMsgMutation } from "../../app/services/contact";
import { useReplyMessageMutation } from "../../app/services/message";
import { useDispatch } from "react-redux";
export default function useSendMessage(
  props = {
    context: "user",
    from: null,
    to: null,
  }
) {
  const dispatch = useDispatch();
  const { context = "user", from = null, to = null } = props;
  const [
    replyMessage,
    { isError: replyErr, isLoading: replying, isSuccess: replySuccess },
  ] = useReplyMessageMutation();
  const [
    sendChannelMsg,
    {
      isLoading: channelSending,
      isSuccess: channelSuccess,
      isError: channelError,
    },
  ] = useSendChannelMsgMutation();
  const [
    sendUserMsg,
    { isLoading: userSending, isSuccess: userSuccess, isError: userError },
  ] = useSendMsgMutation();
  const sendFn = context == "user" ? sendUserMsg : sendChannelMsg;
  const sendMessages = async ({
    type = "text",
    content,
    users = [],
    channels = [],
  }) => {
    if (users.length) {
      for await (const uid of users) {
        await sendUserMsg({
          type,
          id: uid,
          content,
        });
      }
    }
    if (channels.length) {
      for await (const cid of channels) {
        await sendChannelMsg({
          type,
          id: cid,
          content,
        });
      }
    }
  };
  const sendMessage = async ({
    type = "text",
    content,
    properties = {},
    reply_mid = null,
    ...rest
  }) => {
    if (reply_mid) {
      dispatch(removeReplyingMessage(to));
      await replyMessage({
        id: to,
        reply_mid,
        type,
        content,
        context,
        from_uid: from,
      });
    } else {
      await sendFn({
        id: to,
        content,
        properties: { ...properties },
        type,
        from_uid: from,
        ...rest,
      });
    }
  };
  return {
    sendMessages,
    sendMessage,
    isError: channelError || userError || replyErr,
    isSending: userSending || channelSending || replying,
    isSuccess: channelSuccess || userSuccess || replySuccess,
  };
}
