import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { jwtDecode } from 'jwt-decode';
import type { LoginRequest, User } from '@/api/types';
import apiClient from '@/api';
import { loginWithFetch, logout as apiLogout } from '@/api/auth';
import router from '@/router'; // 导入 Vue Router 实例

// 定义从JWT解码出的负载的类型, 它继承自 User 类型
interface JwtPayload extends User {
  iat: number; // Issued At
  exp: number; // Expiration Time
  sub: string; // Subject, typically the user's email or ID
}

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

  /**
   * 从 token 解码并设置 user state
   * @param tokenValue - JWT token string
   */
  function setUserFromToken(tokenValue: string) {
    try {
      const decoded = jwtDecode<JwtPayload>(tokenValue);
      // 解码出的信息直接赋值给 user state
      user.value = decoded;
    } catch (error) {
      console.error('Failed to decode token or token is invalid:', error);
      // 解码失败时, 清理状态
      user.value = null;
      token.value = null;
      localStorage.removeItem('token');
    }
  }

  // 初始化时，如果localStorage中存在 token，则从中恢复用户信息
  if (token.value) {
    setUserFromToken(token.value);
  }

  const isLoggedIn = computed(() => !!token.value && !!user.value);

  /**
   * 设置认证信息
   * @param newToken - JWT
   */
  function setAuth(newToken: string) {
    token.value = newToken;
    localStorage.setItem('token', newToken);
    setUserFromToken(newToken);
  }

  /**
   * 用户登录
   * @param credentials - 登录凭据
   */
  async function login(credentials: LoginRequest) {
    try {
      const response = await loginWithFetch(credentials);
      const newToken = response.accessToken;

      if (!newToken) {
        throw new Error('accessToken not found in login response');
      }

      setAuth(newToken);

      // 登录成功后，根据用户角色进行重定向
      if (user.value) {
        switch (user.value.role) {
          case 'GRID_WORKER':
            router.push('/my-tasks');
            break;
          case 'ADMIN':
          case 'DECISION_MAKER':
            router.push('/dashboard');
            break;
          case 'SUPERVISOR':
          case 'PUBLIC_SUPERVISOR':
            router.push('/feedback');
            break;
          default:
            // 对于其他未知角色，可以重定向到登录页或一个通用的欢迎页
            router.push('/login');
            break;
        }
      } else {
        // 如果用户信息未设置，则默认重定向到主页
        router.push('/');
      }

    } catch (error: any) {
      console.error('Login process failed:', error);
      delete apiClient.defaults.headers.common['Authorization'];
      throw error;
    }
  }

  /**
   * 用户登出
   */
  async function logout() {
    try {
      // 调用后端的登出接口以记录日志
      await apiLogout();
    } catch (error) {
      console.error('Failed to call logout API, but proceeding with client-side logout:', error);
    } finally {
      // 无论后端调用是否成功，都清理前端状态
      user.value = null;
      token.value = null;
      localStorage.removeItem('token');
      // 登出后重定向到登录页
      router.push('/login');
    }
  }
  
  return {
    token,
    user,
    isLoggedIn,
    login,
    logout,
  };
}); 