'use client'

import { useQueryClient } from '@tanstack/react-query'
import { IBaseResponse } from '@/@core/types/api'
import { IPaymentMethodDetails, IUpdatePaymentMethodPayload } from '@/types/data/payment-method'
import { request } from '@/utils'
import { PAYMENT_METHODS_LIST_QUERY_KEY } from './useGetPaymentMethodsList'
import { PAYMENT_METHOD_DETAILS_QUERY_KEY } from './useGetPaymentMethodDetails'
import { useCustomMutation } from '@/hooks/api'

type UpdateArgs = {
  paymentMethodId: string
  payload: IUpdatePaymentMethodPayload
}

export const useUpdatePaymentMethod = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateArgs, IBaseResponse<IPaymentMethodDetails>>(
    ['payment-methods-update'],
    ({ paymentMethodId, payload }) =>
      request({
        url: `/payment-methods/${paymentMethodId}`,
        method: 'PUT',
        data: payload
      }),
    {
      onSuccess: async (_, variables) => {
        await Promise.all([
          queryClient.invalidateQueries({ queryKey: [PAYMENT_METHODS_LIST_QUERY_KEY] }),
          queryClient.invalidateQueries({ queryKey: [PAYMENT_METHOD_DETAILS_QUERY_KEY, variables.paymentMethodId] })
        ])
      }
    }
  )
}
