/**
 * 认证状态管理Store
 * 使用Zustand管理用户认证状态
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { pythonCliAuth, UserProfile, LoginCredentials, RegisterCredentials } from '../services/pythonCliAuth';

interface AuthState {
  // 状态
  isAuthenticated: boolean;
  user: UserProfile | null;
  loading: boolean;
  error: string | null;
  
  // 操作
  login: (credentials: LoginCredentials) => Promise<void>;
  register: (credentials: RegisterCredentials) => Promise<void>;
  logout: () => Promise<void>;
  getCurrentUser: () => Promise<void>;
  updateProfile: (updates: Partial<Pick<UserProfile, 'displayName' | 'avatarUrl'>>) => Promise<void>;
  clearError: () => void;
  setLoading: (loading: boolean) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // 初始状态
      isAuthenticated: false,
      user: null,
      loading: false,
      error: null,

      // 登录
      login: async (credentials: LoginCredentials) => {
        set({ loading: true, error: null });
        
        try {
          const user = await pythonCliAuth.login(credentials);
          set({
            isAuthenticated: true,
            user,
            loading: false,
            error: null
          });
        } catch (error) {
          set({
            loading: false,
            error: error instanceof Error ? error.message : '登录失败',
            isAuthenticated: false,
            user: null
          });
          throw error;
        }
      },

      // 注册
      register: async (credentials: RegisterCredentials) => {
        set({ loading: true, error: null });
        
        try {
          const user = await pythonCliAuth.register(credentials);
          set({
            isAuthenticated: true,
            user,
            loading: false,
            error: null
          });
        } catch (error) {
          set({
            loading: false,
            error: error instanceof Error ? error.message : '注册失败',
            isAuthenticated: false,
            user: null
          });
          throw error;
        }
      },

      // 登出
      logout: async () => {
        set({ loading: true });
        
        try {
          await pythonCliAuth.logout();
          set({ 
            isAuthenticated: false, 
            user: null, 
            loading: false,
            error: null 
          });
        } catch (error) {
          console.error('Logout error:', error);
          // 即使登出失败，也要清除本地状态
          set({ 
            isAuthenticated: false, 
            user: null, 
            loading: false,
            error: null 
          });
        }
      },

      // 获取当前用户信息
      getCurrentUser: async () => {
        set({ loading: true, error: null });
        
        try {
          const user = await pythonCliAuth.getCurrentUser();
          if (user) {
            set({ 
              isAuthenticated: true, 
              user, 
              loading: false 
            });
          } else {
            set({ 
              isAuthenticated: false, 
              user: null, 
              loading: false 
            });
          }
        } catch (error) {
          set({ 
            loading: false, 
            error: error instanceof Error ? error.message : '获取用户信息失败',
            isAuthenticated: false,
            user: null
          });
        }
      },

      // 更新用户资料
      updateProfile: async (updates: Partial<Pick<UserProfile, 'displayName' | 'avatarUrl'>>) => {
        set({ loading: true, error: null });
        
        try {
          await pythonCliAuth.updateProfile(updates);
          
          // 更新本地用户信息
          const currentUser = get().user;
          if (currentUser) {
            set({ 
              user: { ...currentUser, ...updates },
              loading: false 
            });
          }
        } catch (error) {
          set({ 
            loading: false, 
            error: error instanceof Error ? error.message : '更新资料失败'
          });
          throw error;
        }
      },

      // 清除错误
      clearError: () => {
        set({ error: null });
      },

      // 设置加载状态
      setLoading: (loading: boolean) => {
        set({ loading });
      }
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        isAuthenticated: state.isAuthenticated,
        user: state.user
      })
    }
  )
);

// 初始化时检查认证状态
export const initializeAuth = async () => {
  const { getCurrentUser } = useAuthStore.getState();
  
  // 检查是否有有效的会话
  if (pythonCliAuth.isAuthenticated()) {
    await getCurrentUser();
  } else {
    // 清除过期的状态
    useAuthStore.setState({
      isAuthenticated: false,
      user: null,
      loading: false,
      error: null
    });
  }
};

export default useAuthStore;
