import { toast } from "react-hot-toast";
import axiosInstance from "../../util/axiosInstance";
import {
    addCluster,
    setClusters,
    deleteCluster,
} from "../reducers/clusterReducer";
import { updateClusterView } from "../reducers/currentClusterReducer";

export const fetchClusters = () => async (dispatch) => {
    try {
        const { data } = await axiosInstance.get("/clusters");
        dispatch(setClusters(data));
    } catch (error) {
        toast.error(error.response.data.message);
    }
};

export const addNewCluster = (clusterInfo, callback) => async (dispatch) => {
    try {
        const { data } = await axiosInstance.post("/clusters", clusterInfo);
        dispatch(addCluster(data));
        callback(data);
    } catch (error) {
        toast.error(error.response.data.message);
    }
};

export const updateClusterInfo =
    (clusterInfo, callback) => async (dispatch, getState) => {
        try {
            const {
                currentClusterReducer: { currentCluster },
            } = getState();
            const { data } = await axiosInstance.put(
                `/clusters/${currentCluster.id}`,
                clusterInfo
            );
            dispatch(
                updateClusterView({
                    name: data.name,
                    box: data.box,
                    contact: data.contact,
                    remarks: data.remarks,
                })
            );
            callback();
            toast.success("Cluster Info Updated Successfully");
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const deleteClusterFromMap =
    (callback) => async (dispatch, getState) => {
        try {
            const {
                currentClusterReducer: { currentCluster },
            } = getState();
            await axiosInstance.delete(`/clusters/${currentCluster.id}`);
            callback();
            dispatch(deleteCluster(currentCluster.id));
        } catch (error) {
            console.log(error);
            toast.error(error.response.data.message);
        }
    };
