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

interface SendCodeDto {
  phone: string;
}

interface VerifyCodeDto {
  phone: string;
  code: string;
}

interface VerifyCodeResponse {
  access_token: string;
}

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

export const useSendCode = () => {
  const client = useApiClient();

  return useMutation({
    mutationKey: ["auth", "send-code"],
    mutationFn: async (data: SendCodeDto) => {
      const response = await client.post("/auth/send-code", data);
      return response.data;
    },
  });
};

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

  return useMutation({
    mutationKey: ["auth", "verify-code"],
    mutationFn: async (data: VerifyCodeDto) => {
      const response = await client.post<VerifyCodeResponse>(
        "/auth/verify-code",
        data
      );

      const { access_token } = response.data;

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

      setToken(access_token, true);

      const payload = parseJWT(access_token);
      if (payload) {
        const userId =
          payload.user_id ||
          payload.userId ||
          payload.sub ||
          payload.id ||
          null;

        if (userId) {
          setUserId(userId, true);
        }
      }

      return access_token;
    },
  });
};
