import { storeToRefs } from 'pinia' import { useAuthStore } from '~/stores/auth' import { userApi } from '~/api/user' // Authentication composable for managing user auth state via Pinia export const useAuth = () => { const authStore = useAuthStore() const { isInitialized, isAuthenticated, isPlaymate, token, userProfile, wallet, playmateInfo } = storeToRefs(authStore) const restoreAuth = () => { authStore.restoreAuth() } const refreshAuth = async () => { try { await userApi.renewalToken() } catch (error) { console.error('Failed to refresh token:', error) throw error } } const refreshUser = async () => { try { const result = await userApi.getMyInfo() authStore.setUserProfile(result.userProfile) authStore.setWallet(result.wallet) } catch (error) { console.error('Failed to fetch user:', error) } } const refreshPlaymateInfo = async () => { if (!userProfile.value?.playmate || !userProfile.value?.userNo) return try { const result = await userApi.getPlaymateInfo(userProfile.value?.userNo) authStore.setPlaymateInfo(result) } catch (error) { console.error('Failed to fetch playmate info:', error) } } const login = async (type: 'google', googleData: string) => { try { const result = await userApi.loginWithGoogle({ data: googleData }) if (result) { authStore.setAuth(result.token) authStore.setUserProfile(result.userProfile) authStore.setWallet(result.wallet) return result } return null } catch (error) { console.error('Failed to login:', error) return null } } const loginWithEmail = async (email: string) => { try { const result = await userApi.loginWithEmail(email) if (result) { authStore.setAuth(result.token) authStore.setUserProfile(result.userProfile) authStore.setWallet(result.wallet) return result } return null } catch (error) { console.error('Failed to login with email:', error) return null } } const logout = () => { authStore.logout() } return { isInitialized, isAuthenticated, isPlaymate, token, userProfile, wallet, playmateInfo, restoreAuth, refreshAuth, refreshUser, refreshPlaymateInfo, login, loginWithEmail, logout, } }