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

export const fetchData = async (path, method, payload) => {

    let url = new URL(`${AppData.getInstance().getRestUrl()}/${path}`);

    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 (!response.ok) {
            result.message = response.statusText;
            return result;
        }
        result.data = data;
        return result;
    } catch (error) {
        console.error('Fetch Error:', error);
        return null;
    }   
}