import { ref } from 'vue'
import { defineStore } from 'pinia'
import { http } from '@/plugins/http'
async function setAfCuid(cuid) {
    // if (Capacitor.isNativePlatform()) {
    //     AppsFlyer.setCustomerUserId({ cuid })
    // }
}
async function logLogin() {}
async function logRegistraion(methods = 'username') {}
export const useUserStore = defineStore('user', () => {
    const user = ref(null)
    const login = (username, password) => {
        return new Promise((resolve, reject) => {
            http.post('/api/auth/login', { username, password })
                .then(res => {
                    http.setToken(res.token)
                    return get()
                })
                .then(res => {
                    resolve()
                })
                .catch(e => {
                    if (e.message) {
                        reject(e.message)
                    } else if (e.errors.length > 0) {
                        reject(e.errors[0].message)
                    } else {
                        reject(e)
                    }
                })
        })
    }
    const register = (email, username, password, invitor) => {
        return new Promise((resolve, reject) => {
            http.post('api/auth/register', {
                email,
                username,
                password,
                invitor
            })
                .then(res => {
                    http.setToken(res.token)
                    return get()
                })
                .then(res => {
                    resolve()
                })
                .catch(e => {
                    if (e.message) {
                        reject(e.message)
                    } else if (e.errors.length > 0) {
                        reject(e.errors[0].message)
                    } else {
                        reject(e)
                    }
                })
            // http.post('/auth/v1/userRegister', { username, password, invitor })
            //     .then(res => {
            //         http.setToken(res.token)
            //         user.value = res.user
            //         setAfCuid(res.user.id)
            //         logLogin()
            //         if (res.newRegister) logRegistraion()
            //         resolve(res)
            //     })
            //     .catch(e => {
            //         reject(e)
            //     })
        })
    }
    const get = async () => {
        if (!http.token.value) return Promise.reject()
        return http.get('/api/users/my').then(res => {
            user.value = res
        })
    }
    const logout = () => {
        http.setToken(null)
        user.value = null
    }
    return { user, login, get, register, logout }
})
