import AppData from "../Common/AppData";

export const fetchData = async (pathOrUrl, method, payload, 
    useWpRestUrl = true, useAppRestNamespace = true, useRedirectToLogin = false) => {

    let url = pathOrUrl;
    if (useWpRestUrl) {
        let rest_root_url = AppData.getInstance().get('rest_root_url');
        if (!rest_root_url) {
            console.error('No rest_root_url');
        }

        url = `${rest_root_url}/${pathOrUrl}`;

        if (useAppRestNamespace) {
            rest_root_url = `${rest_root_url}/${AppData.getInstance().get('app_rest_namespace')}/`;
            url = new URL(`${rest_root_url}${pathOrUrl}`);
        }
    }

    const allowedMethods = ['POST', 'GET', 'DELETE', 'PUT'];


    if (!allowedMethods.includes(method)) {
        throw new Error('Fetch: Invalid HTTP method');
    }

    let options = { method };
    if (['POST', 'PUT', 'DELETE'].includes(method)) {
        options = {...options, ...{
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }}
    }

    if (method === 'GET') {
        options = {...options, ...{
            headers: {
                'Accept': 'application/json'
            }
        }}
        if (payload) {
            Object.keys(payload).forEach(key => url.searchParams.append(key, payload[key]));
        }
    }

    try {
        const response = await fetch(url, options);

        let result = { status: response.status };
        const data = await response.json();

        if (result?.status === 403 && useRedirectToLogin) {
            const routes = AppData.getInstance().get('routes');
            window.location.hash = routes?.login.hash;
            return;
        }

        if (!response.ok) {
            result.message = data.message;
            return result;
        }
        result.data = data;
        return result;
    } catch (error) {
        console.error('Fetch Error:', error);
        return null;
    }   
}