import { useQuery } from '@tanstack/react-query'
import { getPaymentStatus } from '../../../services/api'
import type { PaymentStatusResponse } from './midtrans'

const FINAL_STATUSES: PaymentStatusResponse['status'][] = [
  'settlement',
  'capture',
  'expire',
  'cancel',
  'deny',
  'refund',
  'chargeback',
]

export function usePaymentStatus(orderId?: string) {
  return useQuery({
    queryKey: ['paymentStatus', orderId],
    queryFn: () => getPaymentStatus(orderId!),
    enabled: !!orderId,
    refetchInterval: (q) => {
      const s = (q.state.data as PaymentStatusResponse | undefined)?.status
      if (!s) return 3000
      return FINAL_STATUSES.includes(s) ? false : 3000
    },
    staleTime: 1000,
  })
}