"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("../../tools/crypto");
const query_1 = require("../../tools/query");
const sdk_1 = require("../sdk");
var Orders;
(function (Orders) {
    function fetchAll(token, isAdmin = false, options = {}) {
        const { page, perPage, sortPath, ascending } = query_1.getDefaults(options);
        const service = isAdmin ? sdk_1.getServices().orders : sdk_1.getServices().myOrders;
        if (!isAdmin) {
            token = crypto_1.getTokenData(token).authToken;
        }
        return sdk_1.clientExecute({
            uri: service
                .page(page)
                .perPage(perPage)
                .sort(sortPath, ascending)
                .build(),
            method: sdk_1.methods.GET,
            token
        });
    }
    Orders.fetchAll = fetchAll;
    function findById(orderId, token, isAdmin = false) {
        const service = isAdmin ? sdk_1.getServices().orders : sdk_1.getServices().myOrders;
        if (!isAdmin) {
            token = crypto_1.getTokenData(token).authToken;
        }
        return sdk_1.clientExecute({
            uri: service.byId(orderId).build(),
            method: sdk_1.methods.GET,
            token
        });
    }
    Orders.findById = findById;
    function create(cartId, cartVersion, orderNumber, token) {
        const { isAnonymous } = crypto_1.getTokenData(token);
        if (isAnonymous) {
            return Promise.reject(new Error('Refusing to create an order anonymously.'));
        }
        return sdk_1.clientExecute({
            uri: sdk_1.getServices().orders.build(),
            method: sdk_1.methods.POST,
            body: {
                id: cartId,
                version: cartVersion,
                orderNumber
            }
        });
    }
    Orders.create = create;
    function update(orderId, orderVersion, actions, token) {
        return sdk_1.clientExecute({
            uri: sdk_1.getServices()
                .orders.byId(orderId)
                .build(),
            method: sdk_1.methods.POST,
            token,
            body: {
                version: orderVersion,
                actions
            }
        });
    }
    Orders.update = update;
    function remove(orderId, orderVersion, token) {
        return sdk_1.clientExecute({
            uri: sdk_1.getServices()
                .orders.byId(orderId)
                .withVersion(orderVersion)
                .build(),
            method: sdk_1.methods.DELETE,
            token
        });
    }
    Orders.remove = remove;
})(Orders = exports.Orders || (exports.Orders = {}));
//# sourceMappingURL=orders.js.map