/**
 * Request Builder
 * 
 * Builds HTTP requests from BrainfishRESTRequest
 * Ported and simplified from Hoppscotch's EffectiveURL and request building logic
 */ /**
 * Builds auth headers from auth configuration
 */ function buildAuthHeaders(auth) {
    const headers = {};
    if (auth.authType === 'basic' && auth.authActive) {
        const credentials = btoa(`${auth.username}:${auth.password}`);
        headers['Authorization'] = `Basic ${credentials}`;
    } else if (auth.authType === 'bearer' && auth.authActive) {
        headers['Authorization'] = `Bearer ${auth.token}`;
    } else if (auth.authType === 'api-key' && auth.authActive) {
        if (auth.addTo === 'HEADERS') {
            headers[auth.key] = auth.value;
        }
    } else if (auth.authType === 'oauth-2' && auth.authActive) {
        // For OAuth2, we'll use the token if available
        if (auth.grantTypeInfo.token) {
            headers['Authorization'] = `Bearer ${auth.grantTypeInfo.token}`;
        }
    }
    return headers;
}
/**
 * Builds auth query parameters
 */ function buildAuthParams(auth) {
    const params = {};
    if (auth.authType === 'api-key' && auth.authActive) {
        if (auth.addTo === 'QUERY_PARAMS') {
            params[auth.key] = auth.value;
        }
    }
    return params;
}
/**
 * Builds request body from body configuration
 */ function buildRequestBody(body, bodyValue) {
    if (!body.body || body.contentType === null) {
        return undefined;
    }
    // Use provided bodyValue if available (from playground editor)
    if (bodyValue !== undefined && bodyValue !== null) {
        if (body.contentType === 'application/json') {
            // Return as-is - user might be editing
            return bodyValue;
        } else if (body.contentType === 'application/x-www-form-urlencoded') {
            // Parse as form data
            const params = new URLSearchParams();
            bodyValue.split('\n').forEach((line)=>{
                const [key, ...valueParts] = line.split(':');
                if (key && valueParts.length > 0) {
                    params.append(key.trim(), valueParts.join(':').trim());
                }
            });
            return params.toString();
        }
        return bodyValue;
    }
    // Use body from request
    if (Array.isArray(body.body)) {
        // Form data
        if (body.contentType === 'multipart/form-data') {
            const formData = new FormData();
            body.body.forEach((item)=>{
                // Note: In a real implementation, isFile would indicate a file upload
                // For now, we just append the string value
                if (typeof item.value === 'string') {
                    formData.append(item.key, item.value);
                } else {
                    // File or Blob value
                    formData.append(item.key, item.value);
                }
            });
            return formData;
        } else if (body.contentType === 'application/x-www-form-urlencoded') {
            // URL encoded form
            const params = new URLSearchParams();
            body.body.forEach((item)=>{
                if (typeof item.value === 'string') {
                    params.append(item.key, item.value);
                }
            });
            return params;
        }
    } else if (typeof body.body === 'string') {
        return body.body;
    }
    return undefined;
}
/**
 * Builds the final URL with path variables and query parameters
 */ function buildURL(endpoint, params, variables, authParams) {
    // Replace path variables (<<variable>> or {variable})
    let url = endpoint;
    variables.forEach((variable)=>{
        // Replace <<variable>> pattern
        url = url.replace(new RegExp(`<<${variable.key}>>`, 'g'), variable.value || '');
        // Replace {variable} pattern
        url = url.replace(new RegExp(`\\{${variable.key}\\}`, 'g'), variable.value || '');
    });
    // Build query string
    const queryParams = new URLSearchParams();
    // Add request params
    params.filter((p)=>p.active && p.key).forEach((param)=>{
        queryParams.append(param.key, param.value);
    });
    // Add auth params
    Object.entries(authParams).forEach(([key, value])=>{
        queryParams.append(key, value);
    });
    // Append query string to URL
    const queryString = queryParams.toString();
    if (queryString) {
        const separator = url.includes('?') ? '&' : '?';
        url = `${url}${separator}${queryString}`;
    }
    return url;
}
/**
 * Builds a complete HTTP request from BrainfishRESTRequest
 */ export function buildRequest(request, options) {
    // Use provided values or fall back to request defaults
    const params = options?.params || request.params;
    const headers = options?.headers || request.headers;
    const variables = options?.variables || request.requestVariables;
    const bodyValue = options?.body;
    // Build auth headers and params
    const authHeaders = buildAuthHeaders(request.auth);
    const authParams = buildAuthParams(request.auth);
    // Build URL
    const url = buildURL(request.endpoint, params, variables, authParams);
    // Build body
    const body = buildRequestBody(request.body, bodyValue ?? undefined);
    // Build headers
    const finalHeaders = {
        ...authHeaders
    };
    headers.filter((h)=>h.active && h.key).forEach((header)=>{
        finalHeaders[header.key] = header.value;
    });
    // Add content-type if body exists (but don't override if already set)
    if (body && request.body.contentType && !finalHeaders['Content-Type']) {
        finalHeaders['Content-Type'] = request.body.contentType;
    }
    // For POST/PUT/PATCH requests without body, add default Content-Type
    // Some APIs require this header even for empty requests
    if (!finalHeaders['Content-Type'] && [
        'POST',
        'PUT',
        'PATCH'
    ].includes(request.method)) {
        finalHeaders['Content-Type'] = 'application/json';
    }
    return {
        url,
        method: request.method,
        headers: finalHeaders,
        body
    };
}
