import { defineStore } from 'pinia';
import { store } from '@/store';
import { http } from "@/utils/request";

export const useUserStore = defineStore({
    id: 'app-user',
    state: () => ({
        userInfo: null,
        token: '22|ua3STGluZFzDeV1nOs4I3S9s2UCDtQp9AtVLT2jN0535e0a5',
        roles: []
    }),
    getters: {
        getUserInfo(state) {
            return state.userInfo || {};
        },
        isLogin(state) {
            return !!state.token;
        }
    },
    actions: {
        login(data) {
            return new Promise((resolve, reject) => {
                http.post('/auth/login', data).then(async (res) => {
                    this.token = res.token;
                    this.fetchUserInfo();
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        },



        fetchUserInfo() {
            return new Promise((resolve, reject) => {
                http.get('/auth/profile').then(async (res) => {
                    this.userInfo = res
                    this.roles = res.role
                    resolve(res);
                }).catch(err => {
                    reject(err);
                })
            });
        },
        resetState() {
            this.token = null;
            this.userInfo = null;
        },

        async logout() {
            return new Promise((resolve, reject) => {
                http.delete('/auth/logout').then(async (res) => {
                    this.resetState();
                }).catch(err => {
                    reject(err);
                });
            });
        },
    },
    persist: true,
});
export function useUserStoreWithOut() {
    return useUserStore(store);
}