import axios from 'axios';
import CryptoJS from 'crypto-js';

export const request = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    withCredentials: true,
    timeout: 100000000000,
});

request.interceptors.response.use(
    (response) => {
        if (response.data && response.data.metadata && typeof response.data.metadata === 'string') {
            try {
                const bytes = CryptoJS.AES.decrypt(response.data.metadata, import.meta.env.VITE_SECRET_CRYPTO);
                const originalText = bytes.toString(CryptoJS.enc.Utf8);
                if (originalText) {
                    response.data.metadata = JSON.parse(originalText);
                }
            } catch (error) {
                console.error('Decryption failed for:', response.config.url, error);
            }
        }
        return response;
    },
    (error) => {
        return Promise.reject(error);
    },
);
