import axios, { AxiosResponse } from 'axios';
import { encrypt, decrypt } from "./encryption";

export interface EncryptedResponseData {
    status: string;
    message:string
    detail:any
}

export interface DecryptedResponseData<T> {
    status?: number;
    message:string
    data?:T
}


const api = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_HOST_CLIENT || 'http://localhost:3000',
    transformRequest: [function (data, headers) {
        // Do whatever you want to transform the data
        
        if(headers['Content-Type'] == 'multipart/form-data') {
            return data;
        }else if(headers['encrypt'] == 'false'){
            return JSON.stringify(data);
        } else {
            const encryptedString = encrypt(JSON.stringify(data));
            return JSON.stringify(encryptedString);
        }
    }],
});

function getCookie(name: string): string | null {
    if (typeof document === 'undefined') return null;
    
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    
    if (parts.length === 2) {
      return parts.pop()?.split(';').shift() || null;
    }
    
    return null;
  }

api.interceptors.request.use(
    (config) => {
        // You can add auth tokens here if needed
        config.headers.Authorization = `Bearer ${getCookie("__token__")}`;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

api.interceptors.response.use(
    (response:AxiosResponse<EncryptedResponseData>): AxiosResponse<DecryptedResponseData<any>> => {
        const res = {
            ...response,
            message:response.data.message,
            data : decrypt(response.data.detail)
        }
        return res;
    },
    (error) => {
        // Handle global errors here
        return Promise.reject(error);
    }
);

export default api;
