import { defineStore } from 'pinia'; import { computed, ref } from 'vue'; import { useToast } from '@/composables/useToast'; import { storeSyncRepo } from '@/data/repositories/storeSyncRepo'; import type { StoreSyncState, StoreSyncStatus } from '@/types/models'; import { STORE_SYNC_STATUSES } from '@/types/models'; import { translate } from '@/utils/translate'; const POLL_INTERVAL_MS = 5000; export const useStoreSyncStore = defineStore('storeSyncStore', () => { const { showError } = useToast(); const status = ref(STORE_SYNC_STATUSES.NOT_SYNCED); const completedAt = ref(null); const isStarting = ref(false); const hasLoadedStatus = ref(false); let isPollingActive = false; let pollTimerId: number | null = null; const isSyncing = computed(() => status.value === STORE_SYNC_STATUSES.SYNCING); const isSynced = computed(() => status.value === STORE_SYNC_STATUSES.SYNCED); const clearPollTimer = () => { if (pollTimerId === null) { return; } window.clearTimeout(pollTimerId); pollTimerId = null; }; const applyState = (state: StoreSyncState) => { status.value = state.status; completedAt.value = state.completedAt; if (isSyncing.value) { schedulePoll(); return; } clearPollTimer(); }; const loadStatus = async () => { const [data, error] = await storeSyncRepo.getStatus(); hasLoadedStatus.value = true; if (error || !data) { if (isSyncing.value) { schedulePoll(); } return; } applyState(data); }; const schedulePoll = () => { if (!isPollingActive || pollTimerId !== null) { return; } pollTimerId = window.setTimeout(() => { pollTimerId = null; loadStatus(); }, POLL_INTERVAL_MS); }; const startPolling = () => { isPollingActive = true; return loadStatus(); }; const stopPolling = () => { isPollingActive = false; clearPollTimer(); }; const startSync = async () => { isStarting.value = true; const [data, error] = await storeSyncRepo.startSync(); isStarting.value = false; if (error || !data) { showError(translate('hostinger_reach_store_sync_error')); return; } applyState(data); }; return { status, completedAt, isStarting, hasLoadedStatus, isSyncing, isSynced, loadStatus, startSync, startPolling, stopPolling }; });