import {create} from "zustand"; import * as api from "@/api/locations"; const useLocationStore = create((set, get) => ({ locations: [], loading: false, error: null, fetchLocations: async () => { set({loading: true, error: null}); try { const data = await api.listLocations(); set({locations: data, loading: false}); } catch (error) { set({error, loading: false}); } }, addLocation: async (location) => { try { const newLoc = await api.addLocation(location); const normalizedLoc = { ...newLoc, imageSource: api.normalizeImageSource(newLoc.image) }; set((state) => ({ locations: [...state.locations, normalizedLoc], })); return normalizedLoc; } catch (error) { set({error, loading: false}); return null; } }, updateLocation: async (id, location) => { try { const updated = await api.updateLocation(id, location); const normalizedLoc = { ...updated, imageSource: api.normalizeImageSource(updated.image) }; const stringId = String(id); set((state) => ({ locations: state.locations.map((loc) => String(loc.id) === stringId ? normalizedLoc : loc ), })); return normalizedLoc; } catch (error) { set({error, loading: false}); return null; } }, deleteLocation: async (id) => { try { const deleted = await api.deleteLocation(id); const stringId = String(id); set((state) => ({ locations: state.locations.filter((loc) => String(loc.id) !== stringId), loading: false, })); return deleted; } catch (error) { set({error, loading: false}); return false; } }, getLocation: (id) => { const location = get().locations.find((loc) => String(loc.id) === String(id)); if (location && !location.imageSource) { return { ...location, imageSource: api.normalizeImageSource(location.image) }; } return location; }, })); export default useLocationStore;