import {useEffect, useState} from "react";
import {Order} from "../../types/order";
import ordersApi from "../../api/ordersApi";
import {FilterState} from "../../features/filterSlice/filterSlice";

export type Props = {
    productId: number;
    filterState: FilterState;
}
export const parseOrderBy = (orderBy: string): { orderBy: string, desc: boolean } => {
    const ascDesc = orderBy.split('_').at(-1);
    const field = orderBy.split('_').slice(0, -1).join('_');
    if (ascDesc === 'asc') return {orderBy: field, desc: false};
    if (ascDesc === 'desc') return {orderBy: field, desc: true};
    return {orderBy: field, desc: false};
}
const useBarcodeOrders = ({filterState, productId}: Props) => {
    const [orders, setOrders] = useState<Order[]>([]);
    const [isUpdating, setIsUpdating] = useState(false);

    const fetchOrders = async (): Promise<Order[]> => {
        return ordersApi.getOrdersByProduct({
            ...parseOrderBy(filterState.sorting),
            productId: productId,
            shippingWarehouseId: filterState.shippingWarehouseId,
        });
    }
    const refresh = () => {
        setOrders([]);
        setIsUpdating(true);
        fetchOrders().then((fetchedOrders) => {
            setOrders(fetchedOrders);
            setIsUpdating(false);
        });
    }
    useEffect(() => {
        if (productId < 0) return;
        refresh()
    }, [
        productId,
        filterState
    ]);

    return {
        orders,
        refresh,
        isUpdating
    }
}

export default useBarcodeOrders;