import { useAuthStore } from "../store/authStore";
import type { AuthUser } from "../store/authStore";
import { login as apiLogin, logout as apiLogout, refresh as apiRefresh } from "../api/authApi";
import { fetchDefaultEnterpriseId } from "../api/enterpriseContext";

export function useAuth() {
  const user = useAuthStore((state) => state.user);
  const accessToken = useAuthStore((state) => state.accessToken);
  const bootstrapped = useAuthStore((state) => state.bootstrapped);
  const setSession = useAuthStore((state) => state.setSession);
  const clearSession = useAuthStore((state) => state.clearSession);

  async function bindSession(accessToken: string, authUser: AuthUser) {
    const enterpriseId = await fetchDefaultEnterpriseId(accessToken);
    setSession(accessToken, authUser, enterpriseId);
    return authUser;
  }

  return {
    user,
    isAuthenticated: Boolean(user && accessToken),
    bootstrapped,
    async login(email: string, password: string) {
      const data = await apiLogin({ email, password });
      return bindSession(data.access_token, data.user as AuthUser);
    },
    async logout() {
      await apiLogout(accessToken);
      clearSession();
    },
    async refreshSession() {
      const data = await apiRefresh();
      await bindSession(data.access_token, data.user as AuthUser);
    }
  };
}
