"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMixpanelConfigured = exports.trackBatch = exports.track = void 0;
const axios_1 = __importDefault(require("axios"));
const logger_1 = __importDefault(require("../../logger"));
class MixpanelService {
    constructor() {
        this.apiUrl = 'https://api.mixpanel.com/track';
        this.projectToken = null;
        this.projectToken = process.env.MIXPANEL_PROJECT_TOKEN || null;
    }
    /**
     * Track an event using Mixpanel API
     * @param eventName - The name of the event to track
     * @param properties - Properties to send with the event
     * @param distinctId - Optional distinct ID for the user
     */
    async track(eventName, properties = {}, distinctId) {
        try {
            // Check if Mixpanel is configured
            if (!this.projectToken) {
                logger_1.default.warn(`Mixpanel project token not configured. Event not tracked: ${eventName}`);
                return false;
            }
            // Prepare the event data
            const eventData = {
                event: eventName,
                properties: {
                    ...properties,
                    token: this.projectToken,
                    $lib_version: '1.0.0',
                    $lib: 'trusys-server',
                },
                distinct_id: distinctId || 'anonymous',
                timestamp: Math.floor(Date.now() / 1000), // Unix timestamp in seconds
            };
            // Encode the data as base64
            const jsonData = JSON.stringify(eventData);
            const base64Data = Buffer.from(jsonData).toString('base64');
            // Prepare the request
            const requestData = {
                data: base64Data,
            };
            // Send the request to Mixpanel
            const response = await axios_1.default.post(this.apiUrl, requestData, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                timeout: 5000, // 5 second timeout
            });
            // Check if the request was successful
            if (response.status === 200) {
                logger_1.default.debug(`Successfully tracked event: ${eventName}`);
                return true;
            }
            else {
                logger_1.default.warn(`Failed to track event ${eventName}. Status: ${response.status}`);
                return false;
            }
        }
        catch (error) {
            console.error(`Error tracking event ${eventName}:`, error);
            return false;
        }
    }
    /**
     * Track multiple events in a batch
     * @param events - Array of events to track
     */
    async trackBatch(events) {
        try {
            if (!this.projectToken) {
                logger_1.default.warn('Mixpanel project token not configured. Batch events not tracked');
                return false;
            }
            const eventData = events.map(({ event, properties = {}, distinctId }) => ({
                event,
                properties: {
                    ...properties,
                    token: this.projectToken,
                    $lib_version: '1.0.0',
                    $lib: 'trusys-server',
                },
                distinct_id: distinctId || 'anonymous',
                timestamp: Math.floor(Date.now() / 1000),
            }));
            const jsonData = JSON.stringify(eventData);
            const base64Data = Buffer.from(jsonData).toString('base64');
            const requestData = {
                data: base64Data,
            };
            const response = await axios_1.default.post(this.apiUrl, requestData, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                timeout: 10000, // 10 second timeout for batch requests
            });
            if (response.status === 200) {
                logger_1.default.debug(`Successfully tracked ${events.length} events in batch`);
                return true;
            }
            else {
                logger_1.default.warn(`Failed to track batch events. Status: ${response.status}`);
                return false;
            }
        }
        catch (error) {
            logger_1.default.error(`Error tracking batch events: ${error}`);
            return false;
        }
    }
    /**
     * Check if Mixpanel is properly configured
     */
    isConfigured() {
        return this.projectToken !== null;
    }
}
// Create a singleton instance
const mixpanelService = new MixpanelService();
// Export the track function and service instance
const track = (eventName, properties, distinctId) => mixpanelService.track(eventName, properties, distinctId);
exports.track = track;
const trackBatch = (events) => mixpanelService.trackBatch(events);
exports.trackBatch = trackBatch;
const isMixpanelConfigured = () => mixpanelService.isConfigured();
exports.isMixpanelConfigured = isMixpanelConfigured;
exports.default = mixpanelService;
//# sourceMappingURL=index.js.map