import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { UserInfo } from '@/types/auth';

export const useAuthStore = defineStore(
    'auth',
    () => {
        const token = ref<string>('');
        const user = ref<UserInfo | null>(null);

        const isLoggedIn = computed(() => !!token.value);
        const isAdmin = computed(() => user.value?.role === 1);

        const setToken = (newToken: string) => {
            token.value = newToken;
        };

        const setUser = (newUser: UserInfo) => {
            user.value = newUser;
        };

        const logout = () => {
            token.value = '';
            user.value = null;
        };

        return {
            token,
            user,
            isLoggedIn,
            isAdmin,
            setToken,
            setUser,
            logout,
        };
    },
    {
        persist: true, // Auto-save to localStorage
    }
);
