import { useEffect, useState } from "react";
import { cacheData,getCachedData } from "../slices/apiDataManager";
import { MasterRespository } from "../repositories/MastersRepository";


export const useMasterRole =()=>{

  const [masterRole, setMasterRole] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

   const fetchData = async () => {
    
       try {
        const features_cache = getCachedData("masterRole");
        if (!features_cache) {
         MasterRespository.getRoles()
           .then((response) => {
            setMasterRole(response.data);
     
             cacheData("masterRole", response.data);
             setLoading(false)
           })
           .catch((error) => {
             setError("Failed to fetch data.");
           });
        }else{
            if (!masterRole.length) setMasterRole(features_cache);
        }
       } catch (err) {
         setError("Failed to fetch data.");
       } finally {
         setLoading(false);
       }
    };


  useEffect(()=>{
    fetchData();
  },[])


  return {masterRole,loading}
}

export const useFeatures =()=> {
  const [masterFeatures, setMasterFeatures] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

   const fetchData = async () => {
    
       try {
        const features_cache = getCachedData("masterFeatures");
        if (!features_cache) {
         MasterRespository.getFeatures()
           .then((response) => {
            setMasterFeatures(response.data);
     
             cacheData("features", response.data);
             setLoading(false)
           })
           .catch((error) => {
             setError("Failed to fetch data.");
           });
        }else{
            if (!masterFeatures.length) setMasterFeatures(features_cache);
        }
       } catch (err) {
         setError("Failed to fetch data.");
       } finally {
         setLoading(false);
       }
    };


  useEffect(()=>{
    fetchData();
  },[])

  return{masterFeatures,loading}
}