import { laravel_api_instance, get_user_id } from '@/shared/api';
import axios from 'axios';

// Функция для получения куки по имени
const getCookie = (name) => {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
};

const fetchData = (endpoint, options = {}) => {
    if (typeof endpoint !== 'string') {
        throw new Error('endpoint должен быть строкой');
    }

    // Деструктурируем headers из options
    const { method = 'GET', data, params = {}, headers = {}, forceProxy = false } = options;

    // Получаем PHPSESSID
    const isDev = import.meta.env.MODE === 'development';

    const sessionId = isDev
        ? import.meta.env.VITE_DEV_SESSION_ID
        : getCookie('PHPSESSID');


    // Извлекаем путь из endpoint
    const path = endpoint.replace(/^\//, '');
    //
    // console.log('[laravelApiService] fetchData вызван с endpoint:', endpoint);
    // console.log('[laravelApiService] Тип data:', data && data.constructor.name);
    // console.log('[laravelApiService] data instanceof FormData:', data instanceof FormData);

    const isFormData = data instanceof FormData;
    if (isFormData && !forceProxy) {
        //console.log('[laravelApiService] Используем directAxiosInstance для FormData');

        const laravelApiUrl = import.meta.env.VITE_LARAVEL_URL || 'https://api.joywork.ru/api';

        // временный инстанс axios без Content-Type
        const directAxiosInstance = axios.create({
            baseURL: laravelApiUrl,
            withCredentials: laravel_api_instance.defaults.withCredentials,
        });

        const finalHeaders = { ...headers };
        if (sessionId) {
            finalHeaders['X-Session-ID'] = sessionId;
        }

        //logMessage("Sending FormData directly to Laravel API: " + laravelApiUrl + endpoint);
        return directAxiosInstance({
            url: endpoint,
            method,
            data,
            headers: finalHeaders,
            params,
        });
    }

    const finalHeaders = { ...headers };
    if (sessionId) {
        finalHeaders['X-Session-ID'] = sessionId;
    }

    if (isFormData) {
        finalHeaders['Content-Type'] = undefined;
    }

    return laravel_api_instance({
        url: '/deal/index.php',
        method,
        data,
        headers: finalHeaders,
        params: {
            path,
            ...params,
        },
        withCredentials: true
    });
};

export default {
    fetchData,
};