import { useCallback } from "react";
import { useMaterialStore } from "../../../../../store/simulation/useMaterialStore";
import { useStorageUnitStore } from "../../../../../store/simulation/useStorageUnitStore";
import { useProductStore } from "../../../../../store/simulation/useProductStore";
import { useSelectedProduct } from "../../../../../store/simulation/useSimulationStore";

export function useStoreHandler() {
    const { getMaterialById, removeMaterial, setEndTime } = useMaterialStore();
    const { addCurrentMaterial, updateCurrentLoad } = useStorageUnitStore();
    const { getModelUuidByActionUuid } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

    const storeLogStatus = (materialUuid: string, status: string) => {
        echo.info(`${materialUuid}, ${status}`);
    }

    const handleStore = useCallback((action: StorageAction, materialId?: string) => {
        if (!action || action.actionType !== 'store' || !materialId) return;

        const material = getMaterialById(materialId);
        if (!material) return;

        const modelUuid = getModelUuidByActionUuid(selectedProduct.productId, action.actionUuid);
        if (!modelUuid) return;

        setEndTime(material.materialId, performance.now());
        removeMaterial(material.materialId);
        addCurrentMaterial(modelUuid, material.materialType, material.materialId);
        updateCurrentLoad(modelUuid, 1);

        storeLogStatus(material.materialName, `performed Store action`);

    }, [getMaterialById]);

    return {
        handleStore,
    };
}