import { useMutation } from '@apollo/client';
import { useToast } from '@theorchard/suite-components';
import { flattenError } from '@theorchard/suite-frontend';
import MergeArtistMutation from './MergeArtist.gql';
import type {
    MergeLabelParticipantAndArtist,
    MergeLabelParticipantAndArtistVariables,
} from './__generated__/MergeArtist';

export const useMergeArtistMutation = (
    variables: MergeLabelParticipantAndArtistVariables
) => {
    const toast = useToast();
    const [
        mergeLabelParticipantAndArtist,
        mergeLabelParticipantAndArtistResult,
    ] = useMutation<
        MergeLabelParticipantAndArtist,
        MergeLabelParticipantAndArtistVariables
    >(MergeArtistMutation, {
        variables,
        onCompleted: () =>
            toast($t('tools.artistNameUpdateSidecar.artistMergeSuccess'), {
                variant: 'success',
            }),
        onError: () =>
            toast($t('tools.artistNameUpdateSidecar.artistMergeFailed'), {
                variant: 'error',
            }),
    });

    const { data, loading, error } = mergeLabelParticipantAndArtistResult;

    return {
        mergeLabelParticipantAndArtist,
        data: data?.mergeLabelParticipantAndArtist,
        loading,
        error: error && flattenError(error),
    };
};
