import { CredentialType } from '@bubblelab/shared-schemas';
import { ServiceBubble } from '../../../types/service-bubble-class.js';
import { SortlyParamsSchema, SortlyResultSchema, } from './sortly.schema.js';
const SORTLY_API_URL = 'https://api.sortly.co/api/v1';
/**
 * SortlyBubble - Integration with Sortly inventory management
 *
 * Provides operations for interacting with the Sortly API:
 * - List, get, create, update, and delete items
 * - Search items by name
 * - Move items between folders
 * - List custom field definitions
 *
 * @example
 * ```typescript
 * const result = await new SortlyBubble({
 *   operation: 'list_items',
 *   per_page: 10,
 * }).action();
 *
 * const item = await new SortlyBubble({
 *   operation: 'get_item',
 *   item_id: 12345,
 * }).action();
 * ```
 */
export class SortlyBubble extends ServiceBubble {
    static service = 'sortly';
    static authType = 'apikey';
    static bubbleName = 'sortly';
    static type = 'service';
    static schema = SortlyParamsSchema;
    static resultSchema = SortlyResultSchema;
    static shortDescription = 'Sortly inventory management for tracking items, folders, and stock levels';
    static longDescription = `
    Sortly is a visual inventory management platform.
    This bubble provides operations for:
    - Listing and searching inventory items and folders
    - Creating, updating, and deleting items
    - Moving items between folders
    - Listing custom field definitions

    Authentication:
    - Uses API key (available on Ultra/Enterprise plans)
    - Key is passed via Authorization Bearer header

    Use Cases:
    - Automate inventory tracking and stock level monitoring
    - Sync inventory data with external systems
    - Build automated reorder workflows based on min_quantity thresholds
    - Organize items across folders programmatically
  `;
    static alias = 'inventory';
    constructor(params = {
        operation: 'list_items',
    }, context) {
        super(params, context);
    }
    chooseCredential() {
        const params = this.params;
        const credentials = params.credentials;
        if (!credentials || typeof credentials !== 'object') {
            return undefined;
        }
        return credentials[CredentialType.SORTLY_API_KEY];
    }
    async testCredential() {
        const apiKey = this.chooseCredential();
        if (!apiKey)
            return false;
        const response = await fetch(`${SORTLY_API_URL}/items?per_page=1`, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${apiKey}`,
                Accept: 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error('Sortly API key validation failed');
        }
        return true;
    }
    async performAction(context) {
        void context;
        const params = this.params;
        const { operation } = params;
        try {
            switch (operation) {
                case 'list_items':
                    return (await this.listItems(params));
                case 'get_item':
                    return (await this.getItem(params));
                case 'create_item':
                    return (await this.createItem(params));
                case 'update_item':
                    return (await this.updateItem(params));
                case 'delete_item':
                    return (await this.deleteItem(params));
                case 'search_items':
                    return (await this.searchItems(params));
                case 'move_item':
                    return (await this.moveItem(params));
                case 'list_custom_fields':
                    return (await this.listCustomFields());
                default:
                    throw new Error(`Unknown operation: ${operation}`);
            }
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
            return {
                operation,
                success: false,
                error: errorMessage,
            };
        }
    }
    // ---------------------------------------------------------------------------
    // HTTP helper
    // ---------------------------------------------------------------------------
    async makeSortlyRequest(endpoint, method = 'GET', body) {
        const apiKey = this.chooseCredential();
        if (!apiKey)
            throw new Error('Sortly API key is required');
        const url = `${SORTLY_API_URL}${endpoint}`;
        const headers = {
            Authorization: `Bearer ${apiKey}`,
            Accept: 'application/json',
        };
        const init = { method, headers };
        if (body && (method === 'POST' || method === 'PUT')) {
            headers['Content-Type'] = 'application/json';
            init.body = JSON.stringify(body);
        }
        const response = await fetch(url, init);
        if (method === 'DELETE' && response.status === 204) {
            return {};
        }
        if (!response.ok) {
            const text = await response.text();
            throw new Error(`Sortly API error (HTTP ${response.status}): ${text}`);
        }
        return await response.json();
    }
    // ---------------------------------------------------------------------------
    // Operations
    // ---------------------------------------------------------------------------
    async listItems(params) {
        const qs = new URLSearchParams();
        if (params.page)
            qs.set('page', String(params.page));
        if (params.per_page)
            qs.set('per_page', String(params.per_page));
        if (params.folder_id)
            qs.set('folder_id', String(params.folder_id));
        qs.set('include', 'custom_attributes,photos');
        const data = (await this.makeSortlyRequest(`/items?${qs.toString()}`));
        return {
            operation: 'list_items',
            success: true,
            items: data.data || [],
            page: data.page,
            per_page: data.per_page,
            total: data.total,
            error: '',
        };
    }
    async getItem(params) {
        const data = (await this.makeSortlyRequest(`/items/${params.item_id}?include=custom_attributes,photos`));
        return {
            operation: 'get_item',
            success: true,
            item: (data.data || data),
            error: '',
        };
    }
    async createItem(params) {
        const body = { name: params.name };
        if (params.type)
            body.type = params.type;
        if (params.notes)
            body.notes = params.notes;
        if (params.price)
            body.price = params.price;
        if (params.quantity !== undefined)
            body.quantity = params.quantity;
        if (params.min_quantity !== undefined)
            body.min_quantity = params.min_quantity;
        if (params.parent_id)
            body.parent_id = params.parent_id;
        if (params.sid)
            body.sid = params.sid;
        if (params.tags)
            body.tags = params.tags;
        const data = (await this.makeSortlyRequest('/items', 'POST', body));
        return {
            operation: 'create_item',
            success: true,
            item: (data.data || data),
            error: '',
        };
    }
    async updateItem(params) {
        const body = {};
        if (params.name !== undefined)
            body.name = params.name;
        if (params.notes !== undefined)
            body.notes = params.notes;
        if (params.price !== undefined)
            body.price = params.price;
        if (params.quantity !== undefined)
            body.quantity = params.quantity;
        if (params.min_quantity !== undefined)
            body.min_quantity = params.min_quantity;
        if (params.sid !== undefined)
            body.sid = params.sid;
        if (params.tags !== undefined)
            body.tags = params.tags;
        const data = (await this.makeSortlyRequest(`/items/${params.item_id}`, 'PUT', body));
        return {
            operation: 'update_item',
            success: true,
            item: (data.data || data),
            error: '',
        };
    }
    async deleteItem(params) {
        await this.makeSortlyRequest(`/items/${params.item_id}`, 'DELETE');
        return {
            operation: 'delete_item',
            success: true,
            error: '',
        };
    }
    async searchItems(params) {
        const body = { name: params.name };
        if (params.type)
            body.type = params.type;
        if (params.page)
            body.page = params.page;
        if (params.per_page)
            body.per_page = params.per_page;
        const data = (await this.makeSortlyRequest('/items/search', 'POST', body));
        return {
            operation: 'search_items',
            success: true,
            items: data.data || [],
            page: data.page,
            per_page: data.per_page,
            total: data.total,
            error: '',
        };
    }
    async moveItem(params) {
        const body = { quantity: params.quantity };
        if (params.folder_id !== undefined)
            body.folder_id = params.folder_id;
        const data = (await this.makeSortlyRequest(`/items/${params.item_id}/move`, 'POST', body));
        return {
            operation: 'move_item',
            success: true,
            item: (data.data || data),
            error: '',
        };
    }
    async listCustomFields() {
        const data = (await this.makeSortlyRequest('/custom_fields'));
        return {
            operation: 'list_custom_fields',
            success: true,
            custom_fields: data.data || [],
            error: '',
        };
    }
}
//# sourceMappingURL=sortly.js.map