"use client";
import axios, { AxiosHeaders } from "axios";
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { useLocale } from "next-intl";
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { BASE_URL } from "@/utils/url";

export const useGet = ({ url, headers, context = "dashboard", props, }:
    {
        url: string,
        headers?: AxiosHeaders,
        context?: "dashboard" | "special" | "website",
        props?: Omit<UseQueryOptions<any, Error>, 'queryKey' | 'queryFn'>
    }) => {
    const locale = useLocale();
    const token = USER_TOKEN_CL();

    const urlToFetch = context === "special" ? (url) : `${BASE_URL}${url}`;
    const HEADERS = context === "dashboard"
        ? { Authorization: `Bearer ${token}` }
        : (headers ?? {});

    const tag = url?.split('?')[0] ?? "";

    const response = useQuery({
        queryKey: [tag, url, locale, context],
        queryFn: async () => {
            try {
                const response = await axios.get(urlToFetch, { headers: HEADERS });
                return response.data;
            } catch (err: any) {
                if (axios.isAxiosError(err)) {
                    throw new Error(err.response?.data?.message || err.message);
                }
                throw err;
            }
        },
        ...props
    });
    return { ...response }
};