import { ServiceBubble } from '../../../types/service-bubble-class.js';
import { CredentialType } from '@bubblelab/shared-schemas';
import { PylonParamsSchema, PylonResultSchema, } from './pylon.schema.js';
const PYLON_API_BASE = 'https://api.usepylon.com';
export class PylonBubble extends ServiceBubble {
    static type = 'service';
    static service = 'pylon';
    static authType = 'apikey';
    static bubbleName = 'pylon';
    static schema = PylonParamsSchema;
    static resultSchema = PylonResultSchema;
    static shortDescription = 'Pylon B2B support platform for managing issues, messages, accounts, and contacts';
    static longDescription = `
    Pylon is a B2B customer support platform that tracks customer issues across
    multiple channels (Slack, Email, Microsoft Teams, Chat Widget).

    Supported operations:
    - Issues: Create, list, get, and update support issues
    - Messages: Send replies and list messages on issues
    - Accounts: Create, list, and update customer accounts
    - Contacts: List contacts

    Features:
    - Tagging and custom field support
    - Priority and state management for issues
    - Internal notes via private messages
    - Cursor-based pagination
  `;
    static alias = 'pylon';
    constructor(params = {
        operation: 'list_issues',
    }, context) {
        super(params, context);
    }
    async testCredential() {
        const credential = this.chooseCredential();
        if (!credential) {
            throw new Error('Pylon API key is required');
        }
        try {
            const response = await fetch(`${PYLON_API_BASE}/me`, {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${credential}`,
                },
            });
            return response.ok;
        }
        catch {
            return false;
        }
    }
    chooseCredential() {
        const { credentials } = this.params;
        if (!credentials || typeof credentials !== 'object') {
            throw new Error('No Pylon credentials provided');
        }
        return credentials[CredentialType.PYLON_API_KEY];
    }
    async makeApiRequest(endpoint, method = 'GET', body, queryParams) {
        const credential = this.chooseCredential();
        if (!credential) {
            throw new Error('Pylon API key is required');
        }
        let url = `${PYLON_API_BASE}${endpoint}`;
        if (queryParams && Object.keys(queryParams).length > 0) {
            const params = new URLSearchParams(queryParams);
            url += `?${params.toString()}`;
        }
        const headers = {
            Authorization: `Bearer ${credential}`,
            'Content-Type': 'application/json',
        };
        const response = await fetch(url, {
            method,
            headers,
            ...(body ? { body: JSON.stringify(body) } : {}),
        });
        const data = (await response.json());
        return { ok: response.ok, status: response.status, data };
    }
    async performAction(context) {
        void context;
        const { operation } = this.params;
        try {
            const params = this.params;
            const result = await (async () => {
                switch (operation) {
                    case 'create_issue':
                        return await this.createIssue(params);
                    case 'list_issues':
                        return await this.listIssues(params);
                    case 'get_issue':
                        return await this.getIssue(params);
                    case 'update_issue':
                        return await this.updateIssue(params);
                    case 'send_message':
                        return await this.sendMessage(params);
                    case 'list_messages':
                        return await this.listMessages(params);
                    case 'create_account':
                        return await this.createAccount(params);
                    case 'list_accounts':
                        return await this.listAccounts(params);
                    case 'update_account':
                        return await this.updateAccount(params);
                    case 'list_contacts':
                        return await this.listContacts(params);
                    default:
                        throw new Error(`Unknown operation: ${operation}`);
                }
            })();
            return result;
        }
        catch (error) {
            return {
                operation,
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error occurred',
            };
        }
    }
    // ─── Issue Operations ────────────────────────────────────────────────────
    async createIssue(params) {
        const body = {
            title: params.title,
        };
        if (params.body_html)
            body.body_html = params.body_html;
        if (params.assignee_id)
            body.assignee_id = params.assignee_id;
        if (params.priority)
            body.priority = params.priority;
        if (params.tags)
            body.tags = params.tags;
        if (params.account_id)
            body.account_id = params.account_id;
        if (params.requester_email)
            body.requester_email = params.requester_email;
        const { ok, data } = await this.makeApiRequest('/issues', 'POST', body);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'create_issue',
                success: false,
                error: errors.join(', ') || 'Failed to create issue',
            };
        }
        return {
            operation: 'create_issue',
            success: true,
            issue_id: data.data?.id || data.id || '',
            error: '',
        };
    }
    async listIssues(params) {
        const query = {};
        if (params.limit)
            query.limit = String(params.limit);
        if (params.cursor)
            query.cursor = params.cursor;
        if (params.state)
            query.state = params.state;
        const { ok, data } = await this.makeApiRequest('/issues', 'GET', undefined, query);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'list_issues',
                success: false,
                error: errors.join(', ') || 'Failed to list issues',
            };
        }
        return {
            operation: 'list_issues',
            success: true,
            issues: data.data || [],
            cursor: data.cursor,
            error: '',
        };
    }
    async getIssue(params) {
        const { ok, data } = await this.makeApiRequest(`/issues/${encodeURIComponent(params.issue_id)}`);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'get_issue',
                success: false,
                error: errors.join(', ') || 'Failed to get issue',
            };
        }
        return {
            operation: 'get_issue',
            success: true,
            issue: data.data || data,
            error: '',
        };
    }
    async updateIssue(params) {
        const body = {};
        if (params.title !== undefined)
            body.title = params.title;
        if (params.state !== undefined)
            body.state = params.state;
        if (params.priority !== undefined)
            body.priority = params.priority;
        if (params.assignee_id !== undefined)
            body.assignee_id = params.assignee_id;
        if (params.tags !== undefined)
            body.tags = params.tags;
        if (params.tags_apply_mode !== undefined)
            body.tags_apply_mode = params.tags_apply_mode;
        const { ok, data } = await this.makeApiRequest(`/issues/${encodeURIComponent(params.issue_id)}`, 'PATCH', body);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'update_issue',
                success: false,
                error: errors.join(', ') || 'Failed to update issue',
            };
        }
        return {
            operation: 'update_issue',
            success: true,
            error: '',
        };
    }
    // ─── Message Operations ──────────────────────────────────────────────────
    async sendMessage(params) {
        const body = {
            body_html: params.body_html,
        };
        if (params.is_private !== undefined)
            body.is_private = params.is_private;
        const { ok, data } = await this.makeApiRequest(`/issues/${encodeURIComponent(params.issue_id)}/messages`, 'POST', body);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'send_message',
                success: false,
                error: errors.join(', ') || 'Failed to send message',
            };
        }
        return {
            operation: 'send_message',
            success: true,
            message_id: data.data?.id || '',
            error: '',
        };
    }
    async listMessages(params) {
        const query = {};
        if (params.limit)
            query.limit = String(params.limit);
        if (params.cursor)
            query.cursor = params.cursor;
        const { ok, data } = await this.makeApiRequest(`/issues/${encodeURIComponent(params.issue_id)}/messages`, 'GET', undefined, query);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'list_messages',
                success: false,
                error: errors.join(', ') || 'Failed to list messages',
            };
        }
        return {
            operation: 'list_messages',
            success: true,
            messages: data.data || [],
            cursor: data.cursor,
            error: '',
        };
    }
    // ─── Account Operations ──────────────────────────────────────────────────
    async createAccount(params) {
        const body = {
            name: params.name,
        };
        if (params.owner_id)
            body.owner_id = params.owner_id;
        if (params.tags)
            body.tags = params.tags;
        if (params.custom_fields)
            body.custom_fields = params.custom_fields;
        const { ok, data } = await this.makeApiRequest('/accounts', 'POST', body);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'create_account',
                success: false,
                error: errors.join(', ') || 'Failed to create account',
            };
        }
        return {
            operation: 'create_account',
            success: true,
            account_id: data.data?.id || data.id || '',
            error: '',
        };
    }
    async listAccounts(params) {
        const query = {};
        if (params.limit)
            query.limit = String(params.limit);
        if (params.cursor)
            query.cursor = params.cursor;
        const { ok, data } = await this.makeApiRequest('/accounts', 'GET', undefined, query);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'list_accounts',
                success: false,
                error: errors.join(', ') || 'Failed to list accounts',
            };
        }
        return {
            operation: 'list_accounts',
            success: true,
            accounts: data.data || [],
            cursor: data.cursor,
            error: '',
        };
    }
    async updateAccount(params) {
        const body = {};
        if (params.name !== undefined)
            body.name = params.name;
        if (params.owner_id !== undefined)
            body.owner_id = params.owner_id;
        if (params.tags !== undefined)
            body.tags = params.tags;
        if (params.tags_apply_mode !== undefined)
            body.tags_apply_mode = params.tags_apply_mode;
        if (params.custom_fields !== undefined)
            body.custom_fields = params.custom_fields;
        const { ok, data } = await this.makeApiRequest(`/accounts/${encodeURIComponent(params.account_id)}`, 'PATCH', body);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'update_account',
                success: false,
                error: errors.join(', ') || 'Failed to update account',
            };
        }
        return {
            operation: 'update_account',
            success: true,
            error: '',
        };
    }
    // ─── Contact Operations ──────────────────────────────────────────────────
    async listContacts(params) {
        const query = {};
        if (params.limit)
            query.limit = String(params.limit);
        if (params.cursor)
            query.cursor = params.cursor;
        const { ok, data } = await this.makeApiRequest('/contacts', 'GET', undefined, query);
        if (!ok) {
            const errors = data.errors || [];
            return {
                operation: 'list_contacts',
                success: false,
                error: errors.join(', ') || 'Failed to list contacts',
            };
        }
        return {
            operation: 'list_contacts',
            success: true,
            contacts: data.data || [],
            cursor: data.cursor,
            error: '',
        };
    }
}
//# sourceMappingURL=pylon.js.map