import { ref } from 'vue' import { currentUser as apiCurrentUser, loginWithPassword as apiLoginWithPassword, logout as apiLogout, createAccount as apiCreateAccount } from '@/api/auth' import { api } from '@/api/client' import type { User } from '@/domain/types' type Household = { id: number; name: string; slug: string } const user = ref(null) const households = ref([]) const activeHousehold = ref(null) let initialized = false export async function loadUser() { if (!initialized) { user.value = await apiCurrentUser() initialized = true } return user.value } // Legacy username login removed; use loginWithPassword instead. export async function loginWithPassword(email: string, password: string) { user.value = await apiLoginWithPassword(email, password) return user.value } export async function logout() { await apiLogout() user.value = null households.value = [] activeHousehold.value = null } export function setHouseholds(hs: Household[]) { households.value = Array.isArray(hs) ? hs.slice() : [] } export function setActiveHousehold(h: Household | string | null) { if (h == null) { activeHousehold.value = null return } if (typeof h === 'string') { activeHousehold.value = households.value.find((x) => x.slug === h) ?? null } else { activeHousehold.value = h } } export function useAuth() { async function fetchHouseholds(): Promise { const res = await api.GET('/api/v1/users/me/households', { params: {} }) const list = Array.isArray(res.data) ? res.data : [] const hs: Household[] = list.map((h) => ({ id: h.id, name: h.name, slug: h.slug })) setHouseholds(hs) return hs } async function createHousehold(name: string): Promise { const res = await api.POST('/api/v1/households', { body: { name } }) if (!res.response.ok || !res.data) throw new Error('Failed to create household') const h: Household = { id: res.data.id, name: res.data.name, slug: res.data.slug } // Update local state: append and set active setHouseholds([...households.value, h]) setActiveHousehold(h) return h } async function createAccount(email: string, displayName: string, password: string) { const u = await apiCreateAccount(email, displayName, password) user.value = u return u } return { user, households, activeHousehold, loadUser, loginWithPassword, logout, setHouseholds, setActiveHousehold, fetchHouseholds, createHousehold, createAccount } }