import { defineStore } from 'pinia' import { computed, ref } from 'vue' import type { Brand } from '@geo/shared-types' import { brandsApi } from '@/lib/api' import { clearStoredCurrentBrandId, readStoredCurrentBrandId, writeStoredCurrentBrandId, } from '@/lib/current-brand' export const useCompanyStore = defineStore('company', () => { const brands = ref([]) const currentBrandId = ref(readStoredCurrentBrandId()) const loading = ref(false) const initialized = ref(false) const currentBrand = computed( () => brands.value.find((brand) => brand.id === currentBrandId.value) ?? null, ) const hasBrands = computed(() => brands.value.length > 0) function setCurrentBrand(brandId: number | null): void { if (!brandId) { currentBrandId.value = null clearStoredCurrentBrandId() return } currentBrandId.value = brandId writeStoredCurrentBrandId(brandId) } function normalizeBrandList(value: Brand[] | null | undefined): Brand[] { return Array.isArray(value) ? value : [] } function syncCurrentBrand(value: Brand[] | null | undefined): void { const nextBrands = normalizeBrandList(value) const storedId = readStoredCurrentBrandId() const preferredId = currentBrandId.value ?? storedId const matched = preferredId ? nextBrands.find((brand) => brand.id === preferredId) : undefined if (matched) { setCurrentBrand(matched.id) return } if (nextBrands.length > 0) { setCurrentBrand(nextBrands[0].id) return } setCurrentBrand(null) } async function refreshBrands(): Promise { loading.value = true try { const nextBrands = normalizeBrandList(await brandsApi.list()) setBrands(nextBrands) initialized.value = true return nextBrands } finally { loading.value = false } } function setBrands(value: Brand[] | null | undefined): void { const nextBrands = normalizeBrandList(value) brands.value = nextBrands syncCurrentBrand(nextBrands) } function reset(): void { brands.value = [] currentBrandId.value = null initialized.value = false loading.value = false clearStoredCurrentBrandId() } return { brands, currentBrandId, currentBrand, hasBrands, loading, initialized, refreshBrands, setBrands, setCurrentBrand, reset, } })