import { useCallback } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import * as authApi from "@/api/auth.api";
import { extractApiError } from "@/api/axiosInstance";
import {
  authStore,
  clearAuth,
  getRefreshToken,
  setTokens,
  setUser,
} from "@/store/authStore";
import type { LoginRequest, RegisterRequest } from "@/types/auth.types";

export function useAuth() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  const user = authStore.useStore((s) => s.user);
  const accessToken = authStore.useStore((s) => s.accessToken);
  const isAuthenticated = Boolean(accessToken);

  const establishSession = async (tokens: Awaited<ReturnType<typeof authApi.login>>) => {
    setTokens(tokens);
    const me = await authApi.fetchCurrentUser();
    setUser(me);
    return me;
  };

  const loginMutation = useMutation({
    mutationFn: async (payload: LoginRequest) => establishSession(await authApi.login(payload)),
  });

  const registerMutation = useMutation({
    mutationFn: async (payload: RegisterRequest) =>
      establishSession(await authApi.register(payload)),
  });

  const logout = useCallback(async () => {
    const refreshToken = getRefreshToken();
    try {
      if (refreshToken) {
        await authApi.logout(refreshToken);
      }
    } finally {
      clearAuth();
      queryClient.clear();
    }
  }, [queryClient]);

  return {
    user,
    isAuthenticated,
    login: loginMutation.mutateAsync,
    loginPending: loginMutation.isPending,
    loginError: loginMutation.isError
      ? extractApiError(loginMutation.error, t("errors.signInFailed"))
      : null,
    resetLoginError: loginMutation.reset,
    register: registerMutation.mutateAsync,
    registerPending: registerMutation.isPending,
    registerError: registerMutation.isError
      ? extractApiError(registerMutation.error, t("errors.registerFailed"))
      : null,
    resetRegisterError: registerMutation.reset,
    logout,
  };
}
