import { useCallback, useContext } from 'react';
import { StringSchemaDefinition } from 'mongoose';
import { faker } from '@faker-js/faker';

import { BinnerContext } from '../../context/BinnerContext';
import { useGetProcessorIdByBarcodeId } from '../../hooks';
import { addToBin } from '@/app/lib/data/binned';
import { Defect } from '@/app/lib/defect.enum';
import { Product } from '@/app/lib/product.enum';

export const useBinHandler = () => {
    const { bin, item, setBin, setItem } = useContext(BinnerContext);
    const getProcessorIdByBarcodeId = useGetProcessorIdByBarcodeId();

    return useCallback(async (farm: string | null, reason: Defect) => {
        if (!item || bin === null) return;
        
        const binnedItem = {
            ...item,
            farm: farm as StringSchemaDefinition || undefined,
            operator: faker.helpers.arrayElement(['Steve', 'Leighann', 'Lwanda', 'Xueliang', 'Jose']),
            processor: getProcessorIdByBarcodeId(item.processor) as StringSchemaDefinition,
            reason,
        };
        await addToBin(bin, binnedItem);
        setBin(null);
        setItem(null);
    }, [bin, item, setBin, setItem]);
};
