/** * Property store - Zustand store for property state management */ import { create } from 'zustand' import type { Property } from './types' import { getActiveProperty, getUserProperties, setActiveProperty as setActivePropertyAction, } from './actions' interface PropertyStore { // State activeProperty: Property | null properties: Property[] isLoading: boolean error: string | null // Actions fetchProperties: () => Promise fetchActiveProperty: () => Promise setActiveProperty: (propertyId: string) => Promise initialize: () => Promise } export const usePropertyStore = create((set, get) => ({ // Initial state activeProperty: null, properties: [], isLoading: true, error: null, // Fetch all properties fetchProperties: async () => { const result = await getUserProperties() if (result.success) { set({ properties: result.data || [], error: null }) } else { set({ error: result.error || 'Failed to fetch properties', properties: [] }) } }, // Fetch the active property from database fetchActiveProperty: async () => { set({ isLoading: true }) const result = await getActiveProperty() if (result.success) { set({ activeProperty: result.data || null, isLoading: false, error: null }) // If no active property, auto-select the first one if (!result.data) { const propertiesResult = await getUserProperties() if (propertiesResult.success && propertiesResult.data && propertiesResult.data.length > 0) { const firstProperty = propertiesResult.data[0] if (firstProperty) { await get().setActiveProperty(firstProperty.id) } } } } else { set({ error: result.error || 'Failed to fetch active property', activeProperty: null, isLoading: false }) } }, // Set active property setActiveProperty: async (propertyId: string) => { set({ isLoading: true }) // Update database const result = await setActivePropertyAction(propertyId) if (result.success) { // Fetch properties to get the full property object const propertiesResult = await getUserProperties() if (propertiesResult.success && propertiesResult.data) { const selectedProperty = propertiesResult.data.find(p => p.id === propertyId) if (selectedProperty) { set({ activeProperty: selectedProperty, properties: propertiesResult.data, isLoading: false, error: null }) } else { set({ isLoading: false, error: 'Property not found' }) } } else { set({ isLoading: false, error: 'Failed to fetch properties' }) } } else { set({ isLoading: false, error: result.error || 'Failed to set active property' }) } }, // Initialize - fetch both properties and active property initialize: async () => { set({ isLoading: true }) await Promise.all([ get().fetchProperties(), get().fetchActiveProperty(), ]) }, }))