import { useToast } from '@theorchard/suite-components';
import { useUpdateEarningsTransfer } from 'src/apollo/mutations/contract-earnings-transfer';
import type {
    AbacusEarningsTransferTypes,
    AbacusEarningsTransferUpdateInput,
} from 'src/apollo/definitions/globalTypes';
import type { TransferRow } from 'src/types/abacus-contract-earnings-transfer';

export const useUpdateHandler = (contractId: string) => {
    const updateEarningsTransfer = useUpdateEarningsTransfer(contractId);
    const toast = useToast();

    return async (
        earningsTransferId: string,
        transferType: AbacusEarningsTransferTypes,
        row: TransferRow
    ) => {
        await updateEarningsTransfer({
            variables: {
                earningsTransfer: [
                    {
                        earningsTransferId,
                        fromContractId: row.fromContractId,
                        toContractId: row.toContractId!,
                        transferType,
                        transferAmount: parseFloat(row.transferAmount) || 0,
                        rateType: row.rateType ?? undefined,
                        input: row.input ?? undefined,
                        active: row.active,
                        negative: row.negative,
                        useStaticBalance: row.useStaticBalance,
                    } satisfies AbacusEarningsTransferUpdateInput,
                ],
            },
        });

        toast('Transfer of earnings has been successfully updated.');
    };
};
