import { useMutation } from "@tanstack/react-query";
import useAuthStore from "@/stores/useAuthStore";
import useApiClient from "@/hooks/useApiClient";

interface AuthDataType {
  email: string;
  password: string;
  rememberMe: boolean;
}

interface JWTPayload {
  user_id?: number;
  userId?: number;
  sub?: string;
  id?: number;
  [key: string]: unknown;
}

const parseJWT = (token: string): JWTPayload | null => {
  try {
    const base64Url = token.split(".")[1];
    if (!base64Url) {
      return null;
    }

    const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split("")
        .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
        .join("")
    );

    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error("Ошибка при парсинге JWT токена:", error);
    return null;
  }
};

const useAuthentificate = () => {
  const client = useApiClient();
  const setToken = useAuthStore((state) => state.setToken);
  const setUserId = useAuthStore((state) => state.setUserId);

  return useMutation({
    mutationKey: ["auth"],
    mutationFn: async (authData: AuthDataType) => {
      const response = await client.post("/auth/login/", authData);

      const { access_token } = await response.data;

      if (!access_token) {
        throw new Error("Не удалось получить токен авторизации");
      }

      setToken(access_token, authData.rememberMe);

      // Парсим JWT токен и извлекаем userId
      const payload = parseJWT(access_token);
      if (payload) {
        const userId =
          payload.user_id ||
          payload.userId ||
          payload.sub ||
          payload.id ||
          null;

        if (userId) {
          setUserId(userId, authData.rememberMe);
        }
      }

      return access_token;
    },
    onError: () => {
      throw new Error("Ошибка авторизации");
    },
  });
};

export default useAuthentificate;
