import { QUERY_KEYS } from "@/utils/query-key";
import { useMutation } from "@tanstack/react-query";
import { postLogin } from "./_requests";
import { LoginRequest, LoginResponse } from "@/types/auth";
import toast from "react-hot-toast";

export const useLogin = () => {
  return useMutation({
    mutationKey: [QUERY_KEYS.ADMIN_LOGIN],
    mutationFn: (credentials: LoginRequest) => postLogin(credentials),
    onSuccess: (response: LoginResponse) => {
      localStorage.setItem("admin_token", response.tokens.access_token);
      localStorage.setItem(
        "admin_refresh_token",
        response.tokens.refresh_token
      );
      localStorage.setItem("admin_user", JSON.stringify(response.admin_user));
      localStorage.setItem(
        "admin_permissions",
        JSON.stringify(response.permissions)
      );

      toast.success("ورود موفقیت‌آمیز بود");
    },
    onError: (error: any) => {
      console.error("Login error:", error);
      toast.error(error?.message || "خطا در ورود");
    },
  });
};
