import { defineStore } from 'pinia' import { ref, computed } from 'vue' export interface RegionConfig { country_code: string name: string currency: string default_vat_rate: number locale_code: string timezone: string is_active: boolean } export const useRegionStore = defineStore('region', () => { // ── State ────────────────────────────────────────────────────────── const regions = ref([]) const activeRegion = ref(null) const isLoading = ref(false) const error = ref(null) // ── Getters ──────────────────────────────────────────────────────── const defaultRegion = computed(() => { return regions.value.find(r => r.country_code === 'DEFAULT') || null }) const regionMap = computed(() => { const map = new Map() for (const r of regions.value) { map.set(r.country_code, r) } return map }) const activeCurrency = computed(() => { return activeRegion.value?.currency || defaultRegion.value?.currency || 'EUR' }) const activeLocale = computed(() => { return activeRegion.value?.locale_code || defaultRegion.value?.locale_code || 'en-EU' }) const activeVatRate = computed(() => { return activeRegion.value?.default_vat_rate ?? defaultRegion.value?.default_vat_rate ?? 0 }) const activeTimezone = computed(() => { return activeRegion.value?.timezone || defaultRegion.value?.timezone || 'Europe/Brussels' }) // ── Actions ──────────────────────────────────────────────────────── /** * Fetch all active regions from the public API endpoint. * Called once on app initialization. */ async function fetchRegions() { if (regions.value.length > 0) return // already loaded isLoading.value = true error.value = null try { const data = await $fetch('/api/v1/system/regions') regions.value = data || [] } catch (err: any) { error.value = err?.data?.detail || err?.message || 'Failed to load regions' console.error('[RegionStore] Fetch error:', err) } finally { isLoading.value = false } } /** * Set the active region by country_code. * Falls back to DEFAULT if the code is not found. */ function setActiveRegion(countryCode: string) { const found = regions.value.find(r => r.country_code === countryCode) activeRegion.value = found || defaultRegion.value } /** * Get a region config by country_code. */ function getRegion(countryCode: string): RegionConfig | undefined { return regionMap.value.get(countryCode) } return { // State regions, activeRegion, isLoading, error, // Getters defaultRegion, regionMap, activeCurrency, activeLocale, activeVatRate, activeTimezone, // Actions fetchRegions, setActiveRegion, getRegion, } })