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

export const useCreateHandler = (contractId: string) => {
    const createEarningsTransfer = useCreateEarningsTransfer(contractId);
    const toast = useToast();

    return async (
        transferType: AbacusEarningsTransferTypes,
        rows: TransferRow[]
    ) => {
        await createEarningsTransfer({
            variables: {
                earningsTransfer: rows.map(
                    row =>
                        ({
                            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 AbacusEarningsTransferInput
                ),
            },
        });

        toast(
            rows.length === 1
                ? 'Transfer of earnings has been successfully added.'
                : `${rows.length} transfers of earnings have been successfully added.`
        );
    };
};
