import { ServiceBubble } from '../../../types/service-bubble-class.js';
import { CredentialType, decodeCredentialPayload, } from '@bubblelab/shared-schemas';
import { SalesforceParamsSchema, SalesforceResultSchema, } from './salesforce.schema.js';
const SALESFORCE_API_VERSION = 'v59.0';
/**
 * Salesforce CRM Service Bubble
 *
 * Salesforce integration for querying accounts, contacts,
 * and running arbitrary SOQL queries via the Salesforce REST API.
 * Primary use case: account-level field lookup by business ID or Salesforce ID.
 */
export class SalesforceBubble extends ServiceBubble {
    static type = 'service';
    static service = 'salesforce';
    static authType = 'oauth';
    static bubbleName = 'salesforce';
    static schema = SalesforceParamsSchema;
    static resultSchema = SalesforceResultSchema;
    static shortDescription = 'Salesforce CRM integration for accounts, contacts, and SOQL queries';
    static longDescription = `
    Salesforce CRM integration for querying and searching CRM records.

    Features:
    - Retrieve Account and Contact records by Salesforce ID
    - Search Accounts and Contacts with flexible SOQL WHERE conditions
    - Run arbitrary SOQL queries for any Salesforce object
    - Account-level field lookup by business ID or Salesforce ID
    - Support for custom fields and objects via SOQL

    Security Features:
    - OAuth 2.0 authentication with Salesforce
    - Instance-scoped access (each org has a unique API endpoint)
    - Secure credential handling with base64-encoded payloads
  `;
    static alias = '';
    constructor(params = {
        operation: 'get_account',
        record_id: '',
    }, context) {
        super(params, context);
    }
    async testCredential() {
        const creds = this.parseCredentials();
        if (!creds) {
            throw new Error('Salesforce credentials are required');
        }
        const response = await fetch(`${creds.instanceUrl}/services/data/${SALESFORCE_API_VERSION}/sobjects`, {
            headers: {
                Authorization: `Bearer ${creds.accessToken}`,
                Accept: 'application/json',
            },
        });
        if (!response.ok) {
            const text = await response.text();
            throw new Error(`Salesforce API error (${response.status}): ${text}`);
        }
        return true;
    }
    parseCredentials() {
        const { credentials } = this.params;
        if (!credentials || typeof credentials !== 'object') {
            return null;
        }
        const raw = credentials[CredentialType.SALESFORCE_CRED];
        if (!raw) {
            return null;
        }
        try {
            const parsed = decodeCredentialPayload(raw);
            if (parsed.accessToken && parsed.instanceUrl) {
                return {
                    accessToken: parsed.accessToken,
                    instanceUrl: parsed.instanceUrl.replace(/\/$/, ''),
                };
            }
        }
        catch {
            // If decoding fails, treat the raw value as an access token (validator path)
        }
        return null;
    }
    chooseCredential() {
        const creds = this.parseCredentials();
        return creds?.accessToken;
    }
    async sfRequest(endpoint, method = 'GET', body) {
        const creds = this.parseCredentials();
        if (!creds) {
            throw new Error('Salesforce credentials are required');
        }
        const url = `${creds.instanceUrl}${endpoint}`;
        const init = {
            method,
            headers: {
                Authorization: `Bearer ${creds.accessToken}`,
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
        };
        if (body && method !== 'GET') {
            init.body = JSON.stringify(body);
        }
        const response = await fetch(url, init);
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Salesforce API error (${response.status}): ${errorText}`);
        }
        if (response.status === 204) {
            return undefined;
        }
        return await response.json();
    }
    async performAction(context) {
        void context;
        const { operation } = this.params;
        try {
            const result = await (async () => {
                const p = this.params;
                switch (operation) {
                    case 'get_account':
                        return await this.getAccount(p);
                    case 'search_accounts':
                        return await this.searchAccounts(p);
                    case 'get_contact':
                        return await this.getContact(p);
                    case 'search_contacts':
                        return await this.searchContacts(p);
                    case 'query':
                        return await this.runQuery(p);
                    default:
                        throw new Error(`Unsupported operation: ${operation}`);
                }
            })();
            return result;
        }
        catch (error) {
            return {
                operation,
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error occurred',
            };
        }
    }
    // ─── Operation Implementations ──────────────────────────────────────
    async getAccount(params) {
        const { record_id, fields } = params;
        let endpoint = `/services/data/${SALESFORCE_API_VERSION}/sobjects/Account/${record_id}`;
        if (fields && fields.length > 0) {
            endpoint += `?fields=${fields.join(',')}`;
        }
        const record = (await this.sfRequest(endpoint));
        return {
            operation: 'get_account',
            success: true,
            record,
            error: '',
        };
    }
    async searchAccounts(params) {
        const { where_clause, fields, limit } = params;
        const selectFields = fields && fields.length > 0
            ? fields.join(', ')
            : 'Id, Name, Industry, BillingCity, Website, Phone, AccountNumber, Type';
        const soql = `SELECT ${selectFields} FROM Account WHERE ${where_clause} LIMIT ${limit}`;
        const encoded = encodeURIComponent(soql);
        const data = (await this.sfRequest(`/services/data/${SALESFORCE_API_VERSION}/query?q=${encoded}`));
        return {
            operation: 'search_accounts',
            success: true,
            records: data.records,
            totalSize: data.totalSize,
            done: data.done,
            error: '',
        };
    }
    async getContact(params) {
        const { record_id, fields } = params;
        let endpoint = `/services/data/${SALESFORCE_API_VERSION}/sobjects/Contact/${record_id}`;
        if (fields && fields.length > 0) {
            endpoint += `?fields=${fields.join(',')}`;
        }
        const record = (await this.sfRequest(endpoint));
        return {
            operation: 'get_contact',
            success: true,
            record,
            error: '',
        };
    }
    async searchContacts(params) {
        const { where_clause, fields, limit } = params;
        const selectFields = fields && fields.length > 0
            ? fields.join(', ')
            : 'Id, FirstName, LastName, Email, Phone, AccountId, Title';
        const soql = `SELECT ${selectFields} FROM Contact WHERE ${where_clause} LIMIT ${limit}`;
        const encoded = encodeURIComponent(soql);
        const data = (await this.sfRequest(`/services/data/${SALESFORCE_API_VERSION}/query?q=${encoded}`));
        return {
            operation: 'search_contacts',
            success: true,
            records: data.records,
            totalSize: data.totalSize,
            done: data.done,
            error: '',
        };
    }
    async runQuery(params) {
        const { soql } = params;
        const encoded = encodeURIComponent(soql);
        const data = (await this.sfRequest(`/services/data/${SALESFORCE_API_VERSION}/query?q=${encoded}`));
        return {
            operation: 'query',
            success: true,
            records: data.records,
            totalSize: data.totalSize,
            done: data.done,
            error: '',
        };
    }
}
//# sourceMappingURL=salesforce.js.map