import { createContext, useContext, useEffect, useState } from 'react';
import { api } from '@/api';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user,          setUser]          = useState(undefined); // undefined = loading
  const [singleUserMode, setSUM]          = useState(false);
  const [hasNewVersion,  setHasNewVersion] = useState(false);

  function applyMeResponse(d) {
    setUser(d.user);
    setSUM(d.single_user_mode || false);
    setHasNewVersion(!!d.has_new_version);
  }

  useEffect(() => {
    api.authMode().then(d => {
      if (d.auth_mode === 'single') setSUM(true);
    }).catch(() => {});

    api.me().then(applyMeResponse).catch(() => setUser(null));
  }, []); // eslint-disable-line

  const logout = async () => {
    await api.logout();
    setUser(null);
    setSUM(false);
    setHasNewVersion(false);
  };

  const refresh = () => {
    api.me().then(applyMeResponse).catch(() => {
      setUser(null);
      setSUM(false);
    });
  };

  return (
    <AuthContext.Provider value={{
      user, singleUserMode, setUser, logout, refresh,
      hasNewVersion, setHasNewVersion,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext) || {
    user: null, setUser: () => {}, logout: () => {}, refresh: () => {},
    singleUserMode: false, hasNewVersion: false, setHasNewVersion: () => {},
  };
}
