import { defineStore } from "pinia";
import { store } from '@/store';
import { getLogin } from '@/api/login'
import { LoginData } from "@/api/login/types";
import { useStorage } from '@vueuse/core';

export const userStore = defineStore('user', () => {
    // state
    const token = useStorage("accessToken", "");
    const nickname = ref('');
    const avatar = ref('');

    function login(loginData: LoginData) {
        return new Promise<void>((resolve, reject) => {
            getLogin(loginData)
                .then(({ data }) => {
                    token.value = data.tokenType + " " + data.accessToken;
                    nickname.value = data.nickname;
                    avatar.value = data.avatar;
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    return {
        token,
        nickname,
        avatar,
        login,
    };
})

// 非setup
export function useUserStoreHook() {
    return userStore(store);
}