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

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('user-token') || '',
    userInfo: JSON.parse(localStorage.getItem('user-info') || 'null'),
    tokenExpiry: parseInt(localStorage.getItem('user-token-expiry') || '0'),
  }),
  actions: {
    async login(username, password) {
      try {
        const response = await loginApi({ username, password });
        if (response && response.token) {
          this.token = response.token;
          const payload = JSON.parse(atob(response.token.split('.')[1]));
          this.tokenExpiry = payload.exp * 1000;
          if (response.userInfo) {
            this.userInfo = response.userInfo;
          }
          // 持久化到 localStorage
          localStorage.setItem('user-token', response.token);
          localStorage.setItem('user-info', JSON.stringify(response.userInfo));
          localStorage.setItem('user-token-expiry', this.tokenExpiry.toString());
          return true;
        }
        return false;
      } catch (error) {
        console.error('Login failed:', error);
        return false;
      }
    },
    logout() {
      this.token = '';
      this.userInfo = null;
      this.tokenExpiry = null;
      localStorage.removeItem('user-token');
      localStorage.removeItem('user-info');
      localStorage.removeItem('user-token-expiry');
    },
    isTokenExpired() {
      if (!this.tokenExpiry) return true;
      return Date.now() >= this.tokenExpiry;
    },
  },
  getters: {
    isLoggedIn: (state) => !!state.token && Date.now() < (state.tokenExpiry || 0),
    isAdmin: (state) => state.userInfo?.role === 'ADMIN',
  },
});
