import axios from "axios";

const FRONT_BASE_URL = "https://app.axicon.ir/"
const PRIVATE_BASE_URL = "https://api.axicon.ir/api/"

const axiosParams = {
    withCredentials: true,
    baseURL: PRIVATE_BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': FRONT_BASE_URL,
    }
}
axios.defaults.withXSRFToken = true
const axiosInstance = axios.create(axiosParams);

export const goToLoginPage = () => {
    window.location.href = FRONT_BASE_URL
}
const AdminApi = {
    get: async (url) => {
        try {
            const response = await axiosInstance.get(url);
            return response.data
        } catch (error) {
            if (error.response?.status === 419 || error.response?.status === 401) {
                goToLoginPage()
            } else {
                console.log("error in admin get api")
            }
        }
    },

    delete: async (url) => {
        try {
            const response = await axiosInstance.delete(url);
            return response.data
        } catch (error) {
            if (error.response?.status === 419) {
                goToLoginPage()
            } else {
                console.log("error in admin delete api")
            }
        }
    },

    post: async (url, body, config={}) => {
        try {
            const response = await axiosInstance.post(url, body, config);
            return response.data
        } catch (error) {
            if (error.response?.status === 419) {
                goToLoginPage()
            } else {
                console.log("error in admin post api")
            }
        }
    },

    imagePost: async (url, body) => {
        try {
            const response = await axios.post(PRIVATE_BASE_URL + url, body, {
                withCredentials: true,
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Access-Control-Allow-Origin': FRONT_BASE_URL,
                    'Accept' : 'application/json',
                }
            });
            return response.data
        } catch (error) {
            if (error.response?.status === 419) {
                goToLoginPage()
            } else {
                return error;
            }
        }
    },
}

export default AdminApi;