import { ref } from 'vue';
import api from '../api';

const pendingCount = ref(0);
let pollTimer: ReturnType<typeof setInterval> | null = null;
let pollConsumers = 0;

export async function refreshDepositPendingCount() {
  try {
    const { data } = await api.get('/admin/deposit-orders/pending-count');
    pendingCount.value = Number(data.data?.count ?? 0);
  } catch {
    pendingCount.value = 0;
  }
}

export function useDepositPendingCount() {
  function startDepositPendingPolling() {
    pollConsumers += 1;
    if (pollConsumers > 1) return;
    void refreshDepositPendingCount();
    pollTimer = setInterval(() => void refreshDepositPendingCount(), 30_000);
  }

  function stopDepositPendingPolling() {
    pollConsumers = Math.max(0, pollConsumers - 1);
    if (pollConsumers > 0) return;
    if (pollTimer) {
      clearInterval(pollTimer);
      pollTimer = null;
    }
  }

  return {
    pendingCount,
    refreshDepositPendingCount,
    startDepositPendingPolling,
    stopDepositPendingPolling,
  };
}
