/**
 * Salesforce Bubble Utility Functions
 *
 * Helper functions for Salesforce API interactions and data formatting.
 */
/**
 * Validate Salesforce ID format (15 or 18 character)
 * @param id Salesforce record ID
 * @returns Whether the ID is valid
 */
export function isValidSalesforceId(id) {
    // Salesforce IDs are either 15-character (case-sensitive) or 18-character (case-insensitive)
    return /^[a-zA-Z0-9]{15}$|^[a-zA-Z0-9]{18}$/.test(id);
}
/**
 * Convert 15-character Salesforce ID to 18-character ID
 * @param id15 15-character Salesforce ID
 * @returns 18-character Salesforce ID
 */
export function to18CharId(id15) {
    if (id15.length === 18)
        return id15;
    if (id15.length !== 15) {
        throw new Error('Invalid Salesforce ID: must be 15 or 18 characters');
    }
    const suffix = [];
    for (let i = 0; i < 3; i++) {
        let flags = 0;
        for (let j = 0; j < 5; j++) {
            const char = id15.charAt(i * 5 + j);
            if (char >= 'A' && char <= 'Z') {
                flags += 1 << j;
            }
        }
        suffix.push('ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'.charAt(flags));
    }
    return id15 + suffix.join('');
}
/**
 * Format Salesforce date to ISO string
 * @param sfDate Salesforce date string (YYYY-MM-DD or ISO format)
 * @returns ISO date string
 */
export function formatSalesforceDate(sfDate) {
    // If already ISO format, return as-is
    if (sfDate.includes('T')) {
        return sfDate;
    }
    // Convert YYYY-MM-DD to ISO
    return new Date(sfDate + 'T00:00:00.000Z').toISOString();
}
/**
 * Convert JavaScript Date to Salesforce date format
 * @param date JavaScript Date object
 * @returns Salesforce date string (YYYY-MM-DD)
 */
export function toSalesforceDate(date) {
    return date.toISOString().split('T')[0];
}
/**
 * Escape SOQL special characters in a string
 * @param value String to escape
 * @returns Escaped string safe for SOQL
 */
export function escapeSoql(value) {
    // Escape single quotes, backslashes, and other special characters
    return value
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/\n/g, '\\n')
        .replace(/\r/g, '\\r')
        .replace(/\t/g, '\\t');
}
/**
 * Build a SOQL query string
 * @param sobjectType sObject API name
 * @param fields Array of field names to select
 * @param options Query options (where, orderBy, limit)
 * @returns SOQL query string
 */
export function buildSoqlQuery(sobjectType, fields, options) {
    let query = `SELECT ${fields.join(', ')} FROM ${sobjectType}`;
    if (options?.where) {
        query += ` WHERE ${options.where}`;
    }
    if (options?.orderBy) {
        query += ` ORDER BY ${options.orderBy}`;
    }
    if (options?.limit) {
        query += ` LIMIT ${options.limit}`;
    }
    return query;
}
/**
 * Enhance Salesforce API error messages with helpful hints
 * @param error Original error message or object
 * @param statusCode HTTP status code
 * @returns Enhanced error message
 */
export function enhanceSalesforceErrorMessage(error, statusCode) {
    // Handle array of Salesforce error objects
    if (Array.isArray(error)) {
        const messages = error.map((e) => {
            let msg = e.message;
            if (e.errorCode) {
                msg = `[${e.errorCode}] ${msg}`;
            }
            if (e.fields && e.fields.length > 0) {
                msg += ` (Fields: ${e.fields.join(', ')})`;
            }
            return msg;
        });
        return messages.join('; ');
    }
    // Handle string error
    let errorMsg = error;
    if (statusCode === 401) {
        errorMsg += '\n\nHint: Your Salesforce access token may be expired. Try refreshing your OAuth credentials.';
    }
    else if (statusCode === 403) {
        errorMsg += '\n\nHint: You may not have permission to access this resource. Check your Salesforce profile permissions.';
    }
    else if (statusCode === 404) {
        errorMsg += '\n\nHint: The requested resource was not found. Check that the ID or object type is correct.';
    }
    else if (statusCode === 400) {
        errorMsg += '\n\nHint: The request was malformed. Check your field names and data types.';
    }
    return errorMsg;
}
/**
 * Parse Salesforce API error response
 * @param responseBody Response body from Salesforce API
 * @returns Array of error objects or string error
 */
export function parseSalesforceError(responseBody) {
    if (Array.isArray(responseBody)) {
        return responseBody;
    }
    if (typeof responseBody === 'string') {
        return responseBody;
    }
    if (typeof responseBody === 'object' &&
        responseBody !== null &&
        'message' in responseBody) {
        return [responseBody];
    }
    return 'Unknown Salesforce API error';
}
/**
 * Get the instance URL from OAuth token response metadata
 * @param instanceUrl Instance URL from OAuth response
 * @returns Cleaned instance URL (without trailing slash)
 */
export function cleanInstanceUrl(instanceUrl) {
    return instanceUrl.replace(/\/$/, '');
}
/**
 * Get Salesforce API version
 * @returns Current API version string
 */
export function getSalesforceApiVersion() {
    return 'v59.0'; // Winter '24 release - current stable version
}
/**
 * Build Salesforce REST API URL
 * @param instanceUrl Salesforce instance URL
 * @param endpoint API endpoint path
 * @returns Full API URL
 */
export function buildApiUrl(instanceUrl, endpoint) {
    const cleanedInstance = cleanInstanceUrl(instanceUrl);
    const version = getSalesforceApiVersion();
    // Handle endpoints that already include the services path
    if (endpoint.startsWith('/services/')) {
        return `${cleanedInstance}${endpoint}`;
    }
    // Standard data API endpoints
    return `${cleanedInstance}/services/data/${version}${endpoint}`;
}
//# sourceMappingURL=salesforce.utils.js.map