import { onUnmounted, watch } from 'vue'
import { fetchOrderPaymentStatus } from '../../shared/api'

const POLL_MS = 3000

/**
 * Polls payment status for mengya pending_payment until completed/cancelled or unmount.
 */
export function useMengyaPaymentPolling(orderResult, { onCompleted, onCancelled }) {
  let pollTimer = null

  const stop = () => {
    if (pollTimer != null) {
      clearInterval(pollTimer)
      pollTimer = null
    }
  }

  const start = () => {
    stop()
    if (!orderResult.value?.orderId) return
    if (!(orderResult.value.paymentMethod === 'mengya' && orderResult.value.status === 'pending_payment')) {
      return
    }

    pollTimer = setInterval(async () => {
      const id = orderResult.value?.orderId
      if (!id) return
      try {
        const st = await fetchOrderPaymentStatus(id)
        if (!st?.status) return

        orderResult.value = { ...orderResult.value, status: st.status }

        if (st.status === 'completed') {
          stop()
          await onCompleted()
        } else if (st.status === 'cancelled') {
          stop()
          onCancelled()
        }
      } catch {
        /* ignore poll errors */
      }
    }, POLL_MS)
  }

  watch(
    orderResult,
    (v) => {
      if (!v) {
        stop()
        return
      }
      if (v.paymentMethod === 'mengya' && v.status === 'pending_payment') {
        start()
      } else {
        stop()
      }
    },
    { deep: false }
  )

  onUnmounted(stop)

  return { stopPollingPayment: stop }
}
