import { ZAPIER_BASE_URL } from "../constants";
/**
 * Gets the Zapier base URL from a baseUrl if it matches Zapier hosting patterns.
 * Returns the root domain URL or undefined if not a Zapier domain.
 * This combines domain checking and URL extraction logic.
 */
export function getZapierBaseUrl(baseUrl) {
    if (!baseUrl) {
        return undefined;
    }
    try {
        const url = new URL(baseUrl);
        const hostname = url.hostname;
        // Check if it matches Zapier hosting patterns by examining the last two parts
        const hostParts = hostname.split(".");
        if (hostParts.length < 2) {
            return undefined;
        }
        // Check if any part is "zapier" or starts with "zapier-"
        const hasZapierPart = hostParts.some((part) => part === "zapier" || part.startsWith("zapier-"));
        if (!hasZapierPart) {
            return undefined;
        }
        // Extract root domain using the last two parts
        const rootDomain = hostParts.slice(-2).join(".");
        return `${url.protocol}//${rootDomain}`;
    }
    catch {
        return undefined;
    }
}
/**
 * Returns true if the baseUrl points at a developer's local machine
 * (`localhost` or `127.0.0.1`). Used to relax checks that don't make sense
 * when the SDK API and other services run on different localhost ports.
 */
export function isLocalhostBaseUrl(baseUrl) {
    if (!baseUrl) {
        return false;
    }
    try {
        const { hostname } = new URL(baseUrl);
        return hostname === "localhost" || hostname === "127.0.0.1";
    }
    catch {
        return false;
    }
}
/**
 * Gets tracking base URL with the following precedence:
 * 1. Explicit trackingBaseUrl parameter
 * 2. ZAPIER_TRACKING_BASE_URL environment variable
 * 3. Derive from baseUrl if it's a Zapier domain
 * 4. Use baseUrl directly (whether Zapier-hosted or not)
 * 5. Default to ZAPIER_BASE_URL constant
 */
export function getTrackingBaseUrl({ trackingBaseUrl, baseUrl, }) {
    // 1. Explicit parameter takes highest precedence
    if (trackingBaseUrl) {
        return trackingBaseUrl;
    }
    // 2. Environment variable override
    if (globalThis.process?.env?.ZAPIER_TRACKING_BASE_URL) {
        return globalThis.process?.env?.ZAPIER_TRACKING_BASE_URL;
    }
    // 3. Try to derive from baseUrl if it's a Zapier domain
    if (baseUrl) {
        const zapierBaseUrl = getZapierBaseUrl(baseUrl);
        if (zapierBaseUrl) {
            return zapierBaseUrl;
        }
    }
    // 4. Use baseUrl directly for tracking (whether Zapier-hosted or not)
    if (baseUrl) {
        return baseUrl;
    }
    // 5. Default to ZAPIER_BASE_URL constant
    return ZAPIER_BASE_URL;
}
