/**
 * HAR (HTTP Archive) Request Builder
 * Converts BrainfishRESTRequest to HAR format for HTTPSnippet
 */ /**
 * Build HAR headers from request headers
 */ function buildHarHeaders(request) {
    return request.headers.filter((header)=>header.active).map((header)=>({
            name: header.key,
            value: header.value
        }));
}
/**
 * Build HAR query strings from request params
 */ function buildHarQueryStrings(request) {
    return request.params.filter((param)=>param.active).map((param)=>({
            name: param.key,
            value: param.value
        }));
}
/**
 * Build HAR post params for form data
 */ function buildHarPostParams(body) {
    const result = [];
    for (const entry of body){
        if (!entry.active) continue;
        if (entry.isFile) {
            // Handle file entries
            const values = Array.isArray(entry.value) ? entry.value : [
                entry.value
            ];
            for(let i = 0; i < values.length; i++){
                result.push({
                    name: entry.key,
                    fileName: entry.key,
                    contentType: entry.contentType || 'application/octet-stream'
                });
            }
        } else {
            result.push({
                name: entry.key,
                value: entry.value,
                contentType: entry.contentType
            });
        }
    }
    return result;
}
/**
 * Parse URL-encoded body string to params
 */ function parseUrlEncodedBody(body) {
    if (!body) return [];
    return body.split('\n').map((line)=>{
        const colonIndex = line.indexOf(':');
        if (colonIndex === -1) {
            return {
                name: line.trim(),
                value: ''
            };
        }
        const key = line.slice(0, colonIndex).trim();
        const value = line.slice(colonIndex + 1).trim();
        return {
            name: key,
            value
        };
    });
}
/**
 * Build HAR post data from request body
 */ function buildHarPostData(request) {
    const { contentType, body } = request.body;
    if (!contentType || !body) return undefined;
    // Handle form data types
    if (contentType === 'application/x-www-form-urlencoded') {
        return {
            mimeType: contentType,
            params: typeof body === 'string' ? parseUrlEncodedBody(body) : []
        };
    }
    if (contentType === 'multipart/form-data') {
        return {
            mimeType: contentType,
            params: Array.isArray(body) ? buildHarPostParams(body) : []
        };
    }
    // Handle text-based content types (JSON, XML, HTML, plain text)
    return {
        mimeType: contentType,
        text: typeof body === 'string' ? body : JSON.stringify(body)
    };
}
/**
 * Add authentication headers to the request
 */ function addAuthHeaders(request, headers) {
    const { auth } = request;
    const result = [
        ...headers
    ];
    if (!auth.authActive) return result;
    switch(auth.authType){
        case 'basic':
            {
                if (auth.username && auth.password) {
                    const credentials = btoa(`${auth.username}:${auth.password}`);
                    result.push({
                        name: 'Authorization',
                        value: `Basic ${credentials}`
                    });
                }
                break;
            }
        case 'bearer':
            {
                if (auth.token) {
                    result.push({
                        name: 'Authorization',
                        value: `Bearer ${auth.token}`
                    });
                }
                break;
            }
        case 'api-key':
            {
                if (auth.key && auth.value) {
                    if (auth.addTo === 'HEADERS') {
                        result.push({
                            name: auth.key,
                            value: auth.value
                        });
                    }
                }
                break;
            }
    }
    return result;
}
/**
 * Build URL with query parameters for API key auth
 */ function buildUrlWithApiKeyAuth(request) {
    let url = request.endpoint;
    // Add API key to query params if configured
    if (request.auth.authActive && request.auth.authType === 'api-key' && request.auth.addTo === 'QUERY_PARAMS' && request.auth.key && request.auth.value) {
        const separator = url.includes('?') ? '&' : '?';
        url = `${url}${separator}${encodeURIComponent(request.auth.key)}=${encodeURIComponent(request.auth.value)}`;
    }
    return url;
}
/**
 * Convert BrainfishRESTRequest to HAR Request format
 */ export function buildHarRequest(request) {
    const headers = addAuthHeaders(request, buildHarHeaders(request));
    const url = buildUrlWithApiKeyAuth(request);
    // Add content-type header if body exists and not already present
    if (request.body.contentType && !headers.some((h)=>h.name.toLowerCase() === 'content-type')) {
        headers.push({
            name: 'Content-Type',
            value: request.body.contentType
        });
    }
    return {
        method: request.method,
        url,
        httpVersion: 'HTTP/1.1',
        cookies: [],
        headers,
        queryString: buildHarQueryStrings(request),
        postData: buildHarPostData(request),
        headersSize: -1,
        bodySize: -1
    };
}
