import { ref } from 'vue'
import { defineStore } from 'pinia'
import { http } from '@/plugins/http'

export const useUserStore = defineStore('user', () => {
    const user = ref(null)
    const login = (username, password) => {
        return new Promise((resolve, reject) => {
            http.post('/auth/login', { username, password })
                .then(token => {
                    http.setToken(token)
                    return http.get('/user/my')
                })
                .then(res => {
                    user.value = res
                    resolve(res)
                })
                .catch(e => {
                    reject(e)
                })
        })
    }
    const loginByPhone = (phone, password) => {
        return new Promise((resolve, reject) => {
            http.post('/auth/phonePwdLogin', { phone, password })
                .then(token => {
                    http.setToken(token)
                    return http.get('/user/my')
                })
                .then(res => {
                    user.value = res
                    resolve(res)
                })
                .catch(e => {
                    reject(e)
                })
        })
    }
    const loginByCode = (phone, code, invitor) => {
        return new Promise((resolve, reject) => {
            http.post('/auth/phoneLogin', { phone, code, invitor })
                .then(token => {
                    http.setToken(token)
                    return http.get('/user/my')
                })
                .then(res => {
                    user.value = res
                    resolve(res)
                })
                .catch(e => {
                    reject(e)
                })
        })
    }
    const register = (phone, code, password, invitor) => {
        return new Promise((resolve, reject) => {
            http.post('/auth/register', { phone, code, password, invitor })
                .then(token => {
                    http.setToken(token)
                    return http.get('/user/my')
                })
                .then(res => {
                    user.value = res
                    resolve(res)
                })
                .catch(e => {
                    reject(e)
                })
        })
    }
    const get = async () => {
        if (!http.token.value) return Promise.reject()
        return http.get('/user/my').then(res => {
            user.value = res
        })
    }
    const logout = () => {
        http.setToken(null)
        user.value = null
    }
    return { user, login, get, loginByPhone, loginByCode, register, logout }
})
