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

import api from "../../services/certificatesAPI";
import { CertTypes } from "../../utils/certificates";

const CertificateContext = React.createContext();

const validateCreate = (data) => {
  if (!data.type) throw new Error("type is required");
  if (!data.common_name) throw new Error("common name is required");
};

const callCreateCert = (data, token) => {
  if (data.type === CertTypes.Aftersales) {
    data.tool_id = data.common_name;
    delete data.common_name;
    return api.createAftersales(data, token);
  }

  return api.create(data, token);
};

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

  const createCert = async (data, token) => {
    try {
      setBusy(true);

      validateCreate(data);

      const result = await callCreateCert(data, token);

      if (result.error) {
        throw new Error(`Create certificate error. ${result.message}`);
      }

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

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

export const useCertificateContext = () => useContext(CertificateContext);
