import { defineStore } from 'pinia';
import { login as loginApi } from '../api/CommonApi';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null,
  }),
  actions: {
    async login(username, password) {
      try {
        const response = await loginApi({ username, password });
        if (response && response.token) {
          this.token = response.token;
          if (response.userInfo) {
            this.userInfo = response.userInfo;
          }
          return true;
        }
        return false;
      } catch (error) {
        console.error('Login failed:', error);
        return false;
      }
    },
    logout() {
      this.token = '';
      this.userInfo = null;
    },
  },
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-store',
        storage: sessionStorage,
      }
    ],
  },
});