import React, { useContext, useState } from "react";
import api from "../../services/suppliersAPI";

const SupplierContext = React.createContext();

export const SupplierProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);
  const [suppliers, setSuppliers] = useState([]);
  const [totalSuppliers, setTotalSuppliers] = useState(0);

  const getSuppliers = async (search, token) => {
    try {
      setBusy(true);
      const result = await api.getSuppliers(search, token);
      if (result.error) {
        setSuppliers([]);
        throw new Error(`Get suppliers error. ${result.message}`);
      }
      setSuppliers(result.data ?? []);
      if (result.total) {
        setTotalSuppliers(result.total);
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <SupplierContext.Provider
      value={{
        busy,
        totalSuppliers,
        suppliers,
        getSuppliers,
      }}
    >
      {children}
    </SupplierContext.Provider>
  );
};

export const useSupplierContext = () => useContext(SupplierContext);
