/**
 * KRA - Auth Hook
 * Authentication state management
 */
import { useCallback } from 'react';
import { useModel, history } from '@umijs/max';
import { getToken, setToken, removeToken } from '@/utils/auth';

export function useAuth() {
  const { initialState, setInitialState } = useModel('@@initialState');

  const currentUser = initialState?.currentUser;
  const token = getToken();
  const isLoggedIn = !!token && !!currentUser;

  const login = useCallback(
    async (tokenValue: string, userInfo: any) => {
      setToken(tokenValue);
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    },
    [setInitialState]
  );

  const logout = useCallback(async () => {
    removeToken();
    await setInitialState((s: any) => ({
      ...s,
      currentUser: undefined,
    }));
    history.push('/user/login');
  }, [setInitialState]);

  const refreshUser = useCallback(async () => {
    // Refresh user info from server
    // This should be implemented based on your API
  }, []);

  return {
    currentUser,
    token,
    isLoggedIn,
    login,
    logout,
    refreshUser,
  };
}

export default useAuth;
