"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecombeeApiClient = exports.DeleteUser = exports.MergeUsers = exports.DeleteCartAddition = exports.DeleteBookmark = exports.SetViewPortion = exports.AddRating = exports.AddPurchase = exports.AddDetailView = exports.AddCartAddition = exports.AddBookmark = exports.Batch = void 0;
const actions_core_1 = require("@segment/actions-core");
const crypto_1 = require("crypto");
var DatabaseRegion;
(function (DatabaseRegion) {
    DatabaseRegion["EU_WEST"] = "eu-west";
    DatabaseRegion["CA_EAST"] = "ca-east";
    DatabaseRegion["AP_SE"] = "ap-se";
    DatabaseRegion["US_WEST"] = "us-west";
    DatabaseRegion["CUSTOM"] = "custom";
})(DatabaseRegion || (DatabaseRegion = {}));
function createAddInteractionData(payload) {
    const { additionalData, internalAdditionalData, ...rest } = payload;
    return {
        cascadeCreate: true,
        additionalData: {
            ...(additionalData || {}),
            ...(internalAdditionalData || {})
        },
        ...rest
    };
}
class Request {
    constructor(params, method, path) {
        this.params = params;
        this.method = method;
        this.path = path;
    }
}
class Batch extends Request {
    constructor(requests) {
        super({ requests }, 'POST', '/batch/');
    }
}
exports.Batch = Batch;
class AddBookmark extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/bookmarks/');
    }
}
exports.AddBookmark = AddBookmark;
class AddCartAddition extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/cartadditions/');
    }
}
exports.AddCartAddition = AddCartAddition;
class AddDetailView extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/detailviews/');
    }
}
exports.AddDetailView = AddDetailView;
class AddPurchase extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/purchases/');
    }
}
exports.AddPurchase = AddPurchase;
class AddRating extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/ratings/');
    }
}
exports.AddRating = AddRating;
class SetViewPortion extends Request {
    constructor(params) {
        super(createAddInteractionData(params), 'POST', '/viewportions/');
    }
}
exports.SetViewPortion = SetViewPortion;
function getDeleteUrl(interactionType, params) {
    const url = `/${interactionType}/?userId=${params.userId}&itemId=${params.itemId}`;
    if (params.timestamp !== undefined) {
        if (isNaN(Number(params.timestamp))) {
            return url + `&timestamp=${new Date(params.timestamp).getTime()}`;
        }
        return url + `&timestamp=${params.timestamp}`;
    }
    return url;
}
class DeleteBookmark extends Request {
    constructor(params) {
        super(params, 'DELETE', getDeleteUrl('bookmarks', params));
    }
}
exports.DeleteBookmark = DeleteBookmark;
class DeleteCartAddition extends Request {
    constructor(params) {
        super(params, 'DELETE', getDeleteUrl('cartadditions', params));
    }
}
exports.DeleteCartAddition = DeleteCartAddition;
class MergeUsers extends Request {
    constructor(targetUserId, sourceUserId) {
        super({}, 'PUT', `/users/${targetUserId}/merge/${sourceUserId}?cascadeCreate=true`);
    }
}
exports.MergeUsers = MergeUsers;
class DeleteUser extends Request {
    constructor(userId) {
        super({}, 'DELETE', `/users/${userId}/`);
    }
}
exports.DeleteUser = DeleteUser;
class RecombeeApiClient {
    constructor(settings, request) {
        this.settings = settings;
        this.request = request;
    }
    async send(request) {
        const url = 'https://' + this.getBaseUri() + this.signUrl(request.path);
        const response = await this.request(url, {
            method: request.method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(request.params)
        });
        if (response.headers.get('content-type')?.includes('application/json')) {
            return await response.json();
        }
        else {
            return await response.text();
        }
    }
    getBaseUri() {
        if (this.settings.databaseRegion === DatabaseRegion.CUSTOM) {
            if (!this.settings.apiUri) {
                throw new actions_core_1.InvalidAuthenticationError('RAPI URI is required when using custom database region');
            }
            return this.settings.apiUri;
        }
        const region = this.settings.databaseRegion || DatabaseRegion.EU_WEST;
        return `rapi-${region}.recombee.com`;
    }
    signUrl(path) {
        const hash = 'sha1';
        let url = '/' + this.settings.databaseId + path;
        url += (path.indexOf('?') == -1 ? '?' : '&') + 'hmac_timestamp=' + Math.floor(new Date().getTime() / 1000);
        const hmac = (0, crypto_1.createHmac)(hash, this.settings.privateToken).update(Buffer.from(url)).digest('hex');
        url += '&hmac_sign=' + hmac;
        return url;
    }
}
exports.RecombeeApiClient = RecombeeApiClient;
//# sourceMappingURL=recombeeApiClient.js.map