import { defineStore } from 'pinia';
import apiClient from '../services/api';
import router from '../router';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: localStorage.getItem('accessToken') || null,
    refreshToken: localStorage.getItem('refreshToken') || null,
    user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
    loginError: null,
    isLoadingProfile: false, // 新增：控制profile加载状态
  }),

  getters: {
    isAuthenticated: (state) => !!state.accessToken,
    currentUser: (state) => state.user,
    getLoginError: (state) => state.loginError,
  },

  actions: {
    setAccessToken(token) {
        this.accessToken = token;
        localStorage.setItem('accessToken', token);
        console.log("AuthStore: Access token set.");
    },
    setUser(userData) {
        this.user = userData;
        localStorage.setItem('user', JSON.stringify(userData));
        console.log("AuthStore: User data set:", userData);
    },
    async login(credentials) {
      console.log("AuthStore: Attempting login...", credentials.email);
      this.loginError = null;
      try {
        const response = await apiClient.post('accounts/login/', {
          email: credentials.email,
          password: credentials.password,
        });
        console.log("AuthStore: Login API call successful.", response.data);

        this.setAccessToken(response.data.access);
        this.refreshToken = response.data.refresh;
        localStorage.setItem('refreshToken', this.refreshToken);
        
        await this.fetchUserProfile(); // 登录成功后获取用户资料
        console.log("AuthStore: Login and profile fetch complete.");
        return true;
      } catch (error) {
        const errorMessage = error.response?.data?.detail || 
                             (typeof error.response?.data === 'object' ? Object.values(error.response.data).flat().join(' ') : null) ||
                             error.message || // 从error对象本身取message
                             '登录失败，请检查您的凭据或网络连接。';
        this.loginError = errorMessage;
        console.error('AuthStore: Login action error:', errorMessage, error.response?.data);
        this.clearAuthData(); // 登录失败时清除认证数据
        throw new Error(errorMessage);
      }
    },

    async fetchUserProfile() {
      if (!this.accessToken) {
        console.log("AuthStore: No access token, cannot fetch user profile.");
        this.user = null; // 确保用户数据也清空
        localStorage.removeItem('user');
        return null;
      }
      if (this.isLoadingProfile) {
        console.log("AuthStore: Profile fetch already in progress.");
        return this.user; // 如果正在加载，返回当前user (可能是null)
      }
      console.log("AuthStore: Fetching user profile...");
      this.isLoadingProfile = true;
      try {
        const response = await apiClient.get('accounts/profile/');
        this.setUser(response.data);
        this.isLoadingProfile = false;
        return this.user;
      } catch (error) {
        console.error('AuthStore: Failed to fetch user profile:', error.response?.data || error.message);
        this.isLoadingProfile = false;
        // 响应拦截器会处理401并尝试登出
        // 如果不是401，这里也清除本地用户数据以反映状态
        if (!(error.response && error.response.status === 401)) {
            this.user = null;
            localStorage.removeItem('user');
        }
        // 不再在这里主动调用logout，让响应拦截器或组件决定
        return null;
      }
    },
    clearAuthData() {
        this.accessToken = null;
        this.refreshToken = null;
        this.user = null;
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('user');
        this.loginError = null;
        console.log("AuthStore: Auth data cleared.");
    },
    logout() {
      console.log("AuthStore: Logging out.");
      this.clearAuthData();
      // 登出后，如果当前路由需要认证，跳转到登录页
      // 这个检查也可以放在App.vue的watch中，或者router.beforeEach中（但要避免循环）
      if (router.currentRoute.value.meta.requiresAuth && router.currentRoute.value.name !== 'Login') {
        router.push({ name: 'Login' }).catch(()=>{});
      }
    },

    async tryAutoLogin() {
      console.log("AuthStore: tryAutoLogin called.");
      if (this.accessToken && !this.user) { // 有token但无用户信息
        console.log("AuthStore: Token found, user data missing. Attempting to fetch profile.");
        return await this.fetchUserProfile(); // 返回promise，让调用者知道操作是否完成
      } else if (this.accessToken && this.user) {
        console.log("AuthStore: User already in session from localStorage.");
        return this.user; // 已有用户信息
      } else {
        console.log("AuthStore: No active session for auto-login.");
        return null; // 无会话
      }
    }
  },
});