import type { key_val } from '$lib/stores/ae_stores';

// Updated 2025-01-28
export function add_url_params({
    base_url = '',
    endpoint,
    params,
    log_lvl = 0
}: {
    base_url?: string;
    endpoint: string;
    params: key_val;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** add_url_params() *** base_url=${base_url} endpoint=${endpoint}`,
            params
        );
    }

    const url_obj = new URL(endpoint, base_url);

    Object.keys(params).forEach((key) =>
        url_obj.searchParams.append(key, params[key])
    );

    if (log_lvl) {
        console.log('New URL:', url_obj.toString());
    }

    return url_obj.toString();
    // return 'test';
}

// This is used to clean the header property names. Not underscores allowed in the header names.
// Updated 2025-01-28
export function clean_headers({
    headers,
    log_lvl = 0
}: {
    headers: any;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** clean_headers() ***`, headers);
    }

    const headers_cleaned: key_val = {};
    for (const prop in headers) {
        const prop_cleaned = prop.replaceAll('_', '-');
        if (typeof headers[prop] != 'string') {
            headers[prop] = JSON.stringify(headers[prop]);
        }
        headers_cleaned[prop_cleaned] = headers[prop];
        if (log_lvl > 1) {
            console.log(`${prop_cleaned}: ${headers_cleaned[prop_cleaned]}`);
        }
    }

    // Object.keys(headers).forEach(key => {
    //     if (headers[key]) {
    //         headers_cleaned[key] = headers[key];
    //     }
    // });

    return headers_cleaned;
}
