'use client'

import { useQueryClient } from '@tanstack/react-query'

import type { IBaseResponse } from '@/@core/types/api'
import type { ITransactionSummary } from '@/types/data'
import { request } from '@/utils'
import { PENDING_TRANSACTIONS_QUERY_KEY } from './usePendingTransactions'
import { useCustomMutation } from '@/hooks/api'

type VerifyPayload = {
  transaction_id: string
  verification_notes?: string
}

type RejectPayload = {
  transaction_id: string
  reason: string
}

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

  return useCustomMutation<VerifyPayload, IBaseResponse<ITransactionSummary>>(
    ['transactions-verify'],
    ({ transaction_id, ...payload }) =>
      request({
        url: `/transactions/${transaction_id}/verify`,
        method: 'PATCH',
        data: payload
      }),
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries({ queryKey: [PENDING_TRANSACTIONS_QUERY_KEY] })
      }
    }
  )
}

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

  return useCustomMutation<RejectPayload, IBaseResponse<ITransactionSummary>>(
    ['transactions-reject'],
    ({ transaction_id, reason }) =>
      request({
        url: `/transactions/${transaction_id}/reject`,
        method: 'PATCH',
        data: { reason }
      }),
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries({ queryKey: [PENDING_TRANSACTIONS_QUERY_KEY] })
      }
    }
  )
}
