import React, { useContext, useState } from "react";

import api from "../../services/smsAPI";

const SMSContext = React.createContext();

export class SMS {
  constructor(message, ICCID, isAwaited) {
    /** @type {string} */
    this.messageText = message;
    /** @type {string} */
    this.ICCID = ICCID;
    /** @type {boolean} */
    this.await = isAwaited;
  }
}

/**
 * @param {SMS} data
 */
const validateSend = (data) => {
  if (data == null) {
    throw new Error("No SMS data provided");
  }

  if (!data.messageText) throw new Error("message is required");
  if (!data.ICCID) throw new Error("ICCID is required");
};

export const SMSProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);

  /**
   * @param {SMS} data
   * @param {*} token
   * @returns
   */
  const sendSMS = async (data, token) => {
    try {
      setBusy(true);

      validateSend(data);

      const result = await api.send(data, token);
      if (result.error) {
        throw new Error(`Send message error. ${result.message}`);
      }

      return result;
    } finally {
      setBusy(false);
    }
  };

  return (
    <SMSContext.Provider
      value={{
        busy,
        sendSMS,
      }}
    >
      {children}
    </SMSContext.Provider>
  );
};

export const useSMSContext = () => useContext(SMSContext);
