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

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);

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