"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const config_1 = require("../config");
const properties_1 = require("../properties");
const functions_1 = require("../functions");
const dayjs_1 = __importDefault(require("../../../lib/dayjs"));
const action = {
    title: 'Track Event',
    description: 'Track user events and associate it with their profile.',
    defaultSubscription: 'type = "track"',
    fields: {
        profile: {
            label: 'Profile',
            description: `Properties of the profile that triggered this event.`,
            type: 'object',
            properties: {
                email: {
                    label: 'Email',
                    type: 'string',
                    description: `The user's email to send to Klavio.`,
                    format: 'email'
                },
                phone_number: {
                    label: 'Phone Number',
                    type: 'string'
                },
                country_code: {
                    ...properties_1.country_code
                },
                external_id: {
                    label: 'External Id',
                    description: 'A unique identifier used by customers to associate Klaviyo profiles with profiles in an external system.',
                    type: 'string',
                    default: { '@path': '$.userId' }
                },
                anonymous_id: {
                    label: 'Anonymous Id',
                    description: 'Anonymous user identifier for the user.',
                    type: 'string',
                    default: { '@path': '$.anonymousId' }
                }
            },
            additionalProperties: true,
            required: true
        },
        metric_name: {
            label: 'Metric Name',
            description: 'Name of the event. Must be less than 128 characters.',
            type: 'string',
            default: {
                '@path': '$.event'
            },
            required: true
        },
        properties: {
            description: `Properties of this event.`,
            label: 'Properties',
            type: 'object',
            default: {
                '@path': '$.properties'
            },
            required: true
        },
        time: {
            label: 'Time',
            description: `When this event occurred. By default, the time the request was received will be used.
      The time is truncated to the second. The time must be after the year 2000 and can only
      be up to 1 year in the future.
      `,
            type: 'datetime',
            default: {
                '@path': '$.timestamp'
            }
        },
        value: {
            label: 'Value',
            description: 'A numeric value to associate with this event. For example, the dollar amount of a purchase.',
            type: 'number'
        },
        unique_id: {
            label: 'Unique ID',
            description: `A unique identifier for an event. If the unique_id is repeated for the same
      profile and metric, only the first processed event will be recorded. If this is not
      present, this will use the time to the second. Using the default, this limits only one
      event per profile per second.
      `,
            type: 'string',
            default: {
                '@path': '$.messageId'
            }
        },
        enable_batching: { ...properties_1.enable_batching },
        batch_size: { ...properties_1.batch_size, default: 1000, minimum: 100, maximum: 1000 }
    },
    perform: (request, { payload }) => {
        const { email, phone_number: initialPhoneNumber, external_id, anonymous_id, country_code } = payload.profile;
        const phone_number = (0, functions_1.processPhoneNumber)(initialPhoneNumber, country_code);
        payload.profile.phone_number = phone_number;
        delete payload?.profile?.country_code;
        if (!email && !phone_number && !external_id && !anonymous_id) {
            throw new actions_core_1.PayloadValidationError('One of External ID, Anonymous ID, Phone Number or Email is required.');
        }
        const eventData = {
            data: {
                type: 'event',
                attributes: {
                    properties: { ...payload.properties },
                    time: payload?.time ? (0, dayjs_1.default)(payload.time).toISOString() : undefined,
                    value: payload.value,
                    unique_id: payload.unique_id,
                    metric: {
                        data: {
                            type: 'metric',
                            attributes: {
                                name: payload.metric_name
                            }
                        }
                    },
                    profile: {
                        data: {
                            type: 'profile',
                            attributes: payload.profile
                        }
                    }
                }
            }
        };
        return request(`${config_1.API_URL}/events/`, {
            method: 'POST',
            json: eventData
        });
    },
    performBatch: (request, { payload }) => {
        return (0, functions_1.sendBatchedTrackEvent)(request, payload);
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map