import { create } from 'zustand'; import { apiFetch } from '../lib/api'; import { getDeviceInfo } from '../lib/deviceId'; export interface UserDevice { id: string; deviceId: string; platform: string; model: string | null; name: string | null; lastSeenAt: string; createdAt: string; isCurrent?: boolean; } type DevicesState = { devices: UserDevice[]; maxDevices: number; plan: string; loading: boolean; ensureRegistered: () => Promise; loadDevices: () => Promise; removeDevice: (id: string) => Promise; }; export const useDevicesStore = create((set) => ({ devices: [], maxDevices: 1, plan: 'free', loading: false, ensureRegistered: async () => { const info = await getDeviceInfo().catch(() => null); if (!info) return; await apiFetch('/api/devices/register', { method: 'POST', skipDeviceHeader: true, body: { deviceId: info.deviceId, platform: info.platform, name: info.name, model: info.model, osVersion: info.osVersion, appVersion: info.appVersion, }, }).then((res: any) => { set({ maxDevices: res.max ?? 1 }); }).catch(() => {}); }, loadDevices: async () => { set({ loading: true }); try { await useDevicesStore.getState().ensureRegistered(); const res = await apiFetch<{ devices: UserDevice[]; max: number; plan: string }>( '/api/devices' ); set({ devices: res.devices, maxDevices: res.max, plan: res.plan }); } finally { set({ loading: false }); } }, removeDevice: async (id: string) => { await apiFetch(`/api/devices/${id}`, { method: 'DELETE' }); set((s) => ({ devices: s.devices.filter((d) => d.id !== id) })); }, }));