"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canSetOEUCookie = exports.isValidEdgeLocator = exports.getVisitorIdCookieString = exports.getVisitorId = void 0;
const constants_1 = require("./edge-decider/constants");
const cookie_1 = require("./edge-decider/utils/cookie");
/**
 * Decides between using the default visitor id, which is in the form of an
 * OEUID, and a custom provided visitor id.
 *
 * @param {Object} webManifest
 * @param {Object} inputs
 * @return {string}
 */
function getVisitorId(visitorIdLocator, inputs, logger) {
    let visitorId;
    logger.setLogKey('isCustomVisitorId', !!visitorIdLocator);
    if (!visitorIdLocator) {
        // Default oeuid
        return getOrGenerateOEUId(inputs);
    }
    const { type, name } = visitorIdLocator;
    switch (type) {
        case constants_1.VisitorIdLocatorType.COOKIE:
            visitorId = inputs.cookies && inputs.cookies[name];
            break;
        case constants_1.VisitorIdLocatorType.PAGE_QUERY:
            visitorId = inputs.queryParams?.get(name);
            break;
    }
    if (!visitorId) {
        throw new Error(`Fail to retrieve visitor id. Type: ${type}, Name: ${name}`);
    }
    return visitorId;
}
exports.getVisitorId = getVisitorId;
/**
 * Get or generate an OEU ID.
 *
 * @param {Object} inputs
 * @return {string}
 * @private
 */
function getOrGenerateOEUId(inputs) {
    const currentOEUId = inputs.cookies?.[constants_1.OptimizelyCookies.OEU_ID];
    return currentOEUId || generateRandomVisitorId();
}
/**
 * Generate a random visitor ID as in [user.getID](https://github.com/optimizely/optimizely/blob/06b84fe4c24d26712823dff967db3632093d64fd/src/www/js/client/user.js#L93)
 * @returns {string}
 * @private
 */
function generateRandomVisitorId() {
    // eslint-disable-next-line no-restricted-globals
    return 'oeu' + Date.now() + 'r' + Math.random();
}
/**
 * Construct a cookie string to set the OptimizelyEndUserId in the microsnippet
 * The tracking snippet MAY set the cookie on a more specific domain, but that's ok
 * TODO: maybe integrate with the function getVisitorOUIdCookie
 * @param {String} visitorId
 * @param {String} cookieDomain
 * @param {Number} cookieExpirationDays
 * @param {Boolean} [secureCrossSiteCookies false]
 * @return {String} The microsnippet will write to document.cookie.
 */
function getVisitorIdCookieString(visitorId, cookieDomain = '', cookieExpirationDays = 0, secureCrossSiteCookies = false, logger = undefined) {
    const options = {
        maxAge: cookieExpirationDays
            ? cookieExpirationDays * 24 * 60 * 60
            : constants_1.DEFAULT_COOKIE_EXPIRATION,
        path: '/',
        domain: cookieDomain,
    };
    if (secureCrossSiteCookies) {
        Object.assign(options, cookie_1.SECURE_CROSSSITE_OPTIONS);
    }
    logger.logLifeCycleEvent(`Cookie options: ${JSON.stringify(options)}`);
    return (0, cookie_1.getCookieString)(constants_1.OptimizelyCookies.OEU_ID, visitorId, options);
}
exports.getVisitorIdCookieString = getVisitorIdCookieString;
/**
 * Validates the edge locator object
 * returns false if the locator could not be get on the edge
 *
 * @param locator
 * @returns
 */
function isValidEdgeLocator(locator) {
    // If locator is missing or empty means that it should use OEUId approach
    if (!locator)
        return true;
    return Boolean(locator &&
        [
            constants_1.VisitorIdLocatorType.COOKIE,
            constants_1.VisitorIdLocatorType.PAGE_QUERY,
        ].includes(locator?.type) &&
        locator.name);
}
exports.isValidEdgeLocator = isValidEdgeLocator;
/**
 * Determines whether the OEU cookie should be set.
 * @param inputs
 * @returns
 */
function canSetOEUCookie(inputs) {
    const extendCookieLifetime = inputs.queryParams?.get(constants_1.RequestQueryParameters.EXTEND_COOKIE_LIFETIME) !== 'false' &&
        inputs.requestHeaders?.get(constants_1.OptimizelyRequestHeaders.EXTEND_COOKIE_LIFETIME) !== 'false';
    // The only time we don't set the OEU cookie is when extendCookieLifetime
    // has been set to false and the cookie was previously set.
    return (extendCookieLifetime ||
        typeof inputs.cookies?.[constants_1.OptimizelyCookies.OEU_ID] === 'undefined');
}
exports.canSetOEUCookie = canSetOEUCookie;
exports.default = {
    getVisitorId,
    getVisitorIdCookieString,
    isValidEdgeLocator,
    canSetOEUCookie,
};
