import {useFetchWrapped} from "~/composables/useFetchWrapped";

export const useLoginState = defineStore('loginState', () => {
    const is_logged_in = ref(false)
    const token = ref<string | null>(null)
    const user = ref<UserSchema>({} as UserSchema)

    const checkSession = () => {
        return new Promise<boolean>(resolve => {
            if (!token.value) return resolve(false)
            useFetchWrapped<AuthedRequest, BaseResponse<resp.user.CheckSession>>('App.User_User.CheckSession', {
                token: token.value,
                user_id: user.value.id
            }).then(res => {
                if (res.ret !== 200) {
                    resolve(false)
                    return
                }
                resolve(res.data.is_login)
                // update global state
                is_logged_in.value = res.data.is_login
            }).catch(err => resolve(false))
        })
    }

    const updateProfile = () => {
        return new Promise<UserSchema>((resolve, reject) => {
            if (!token.value) return reject('token is empty')
            useFetchWrapped<AuthedRequest, BaseResponse<resp.user.Profile>>('App.User_User.Profile', {
                token: token.value,
                user_id: user.value.id
            }).then(res => {
                if (res.ret !== 200) {
                    reject(res.msg || '未知错误')
                    return
                }
                user.value = res.data.profile
                resolve(res.data.profile)
            }).catch(err => reject(err || '未知错误'))
        })
    }

    const logout = () => new Promise<void>(resolve => {
        token.value = null
        user.value = {} as UserSchema
        is_logged_in.value = false
        resolve()
    })

    return {
        is_logged_in,
        token,
        user,
        checkSession,
        updateProfile,
        logout
    }
}, {
    persist: {
        key: 'xsh_assistant_persisted_state',
        storage: persistedState.localStorage,
        paths: ['is_logged_in', 'token', 'user']
    }
})