"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultExposureFields = void 0;
exports.sendExposure = sendExposure;
const actions_core_1 = require("@segment/actions-core");
const event_1 = require("./event");
const timestamp_1 = require("./timestamp");
exports.defaultExposureFields = {
    exposure: {
        label: 'ABsmartly Exposure Payload',
        type: 'object',
        defaultObjectUI: 'object:only',
        required: true,
        description: 'The ABsmartly exposure payload without any goals. Generated by the ABsmartly SDK and should not be modified.',
        default: {
            '@path': '$.properties.exposure'
        }
    },
    ...event_1.defaultEventFields
};
function isValidExposureRequest(exposure) {
    if (exposure == null || typeof exposure != 'object') {
        return false;
    }
    const publishedAt = exposure['publishedAt'];
    if (!(0, timestamp_1.isValidTimestamp)(publishedAt)) {
        return false;
    }
    const units = exposure['units'];
    if (!Array.isArray(units) || units.length == 0) {
        return false;
    }
    const exposures = exposure['exposures'];
    if (!Array.isArray(exposures) || exposures.length === 0) {
        return false;
    }
    if (exposures.some((x) => typeof x['exposedAt'] !== 'number' || !(0, timestamp_1.isValidTimestamp)(x['exposedAt']))) {
        return false;
    }
    const goals = exposure['goals'];
    if (goals != null && (!Array.isArray(goals) || goals.length > 0)) {
        return false;
    }
    const attributes = exposure['attributes'];
    if (attributes != null && !Array.isArray(attributes)) {
        return false;
    }
    return true;
}
function sendExposure(request, timestamp, payload, settings) {
    const exposureRequest = payload.exposure;
    if (exposureRequest == null || typeof exposureRequest != 'object') {
        throw new actions_core_1.PayloadValidationError('Field `exposure` is required to be an object when tracking exposures');
    }
    if (!isValidExposureRequest(exposureRequest)) {
        throw new actions_core_1.PayloadValidationError('Field `exposure` is malformed or contains goals. Ensure you are sending a valid ABsmartly exposure payload without goals.');
    }
    const offset = timestamp - (0, timestamp_1.unixTimestampOf)(exposureRequest.publishedAt);
    const exposures = exposureRequest.exposures?.map((x) => ({
        ...x,
        exposedAt: x.exposedAt + offset
    }));
    const attributes = exposureRequest.attributes?.map((x) => ({
        ...x,
        setAt: x.setAt + offset
    }));
    return (0, event_1.sendEvent)(request, settings, {
        ...exposureRequest,
        historic: true,
        publishedAt: timestamp,
        exposures,
        attributes
    }, payload.agent, payload.application);
}
//# sourceMappingURL=exposure.js.map