var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EligibilityService_instances, _EligibilityService_geoCacheTtlMs, _EligibilityService_deps, _EligibilityService_geoLocationCache, _EligibilityService_geoLocationFetchPromise, _EligibilityService_performGeoLocationFetch;
import { successfulFetch } from "@metamask/controller-utils";
import { PERPS_CONSTANTS } from "../constants/perpsConfig.mjs";
import { getEnvironment } from "../utils/index.mjs";
import { ensureError } from "../utils/errorUtils.mjs";
// Geo-blocking API URLs
const ON_RAMP_GEO_BLOCKING_URLS = {
    DEV: 'https://on-ramp.uat-api.cx.metamask.io/geolocation',
    PROD: 'https://on-ramp.api.cx.metamask.io/geolocation',
};
/**
 * EligibilityService
 *
 * Handles geo-location fetching and eligibility checking.
 * Manages caching to minimize API calls.
 *
 * Instance-based service with constructor injection of platform dependencies.
 * Cache is instance-scoped to support multiple service instances (e.g., testing).
 */
export class EligibilityService {
    /**
     * Create a new EligibilityService instance
     *
     * @param deps - Platform dependencies for logging, metrics, etc.
     */
    constructor(deps) {
        _EligibilityService_instances.add(this);
        _EligibilityService_geoCacheTtlMs.set(this, 5 * 60 * 1000); // 5 minutes
        _EligibilityService_deps.set(this, void 0);
        _EligibilityService_geoLocationCache.set(this, null);
        _EligibilityService_geoLocationFetchPromise.set(this, null);
        __classPrivateFieldSet(this, _EligibilityService_deps, deps, "f");
    }
    /**
     * Fetch geo location with caching and deduplication
     *
     * @returns The user's geo location string.
     */
    async fetchGeoLocation() {
        // Check cache first
        if (__classPrivateFieldGet(this, _EligibilityService_geoLocationCache, "f")) {
            const cacheAge = Date.now() - __classPrivateFieldGet(this, _EligibilityService_geoLocationCache, "f").timestamp;
            if (cacheAge < __classPrivateFieldGet(this, _EligibilityService_geoCacheTtlMs, "f")) {
                __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Using cached geo location', {
                    location: __classPrivateFieldGet(this, _EligibilityService_geoLocationCache, "f").location,
                    cacheAge: `${(cacheAge / 1000).toFixed(1)}s`,
                });
                return __classPrivateFieldGet(this, _EligibilityService_geoLocationCache, "f").location;
            }
        }
        // If already fetching, return the existing promise
        if (__classPrivateFieldGet(this, _EligibilityService_geoLocationFetchPromise, "f")) {
            __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Geo location fetch already in progress, waiting...');
            return __classPrivateFieldGet(this, _EligibilityService_geoLocationFetchPromise, "f");
        }
        // Start new fetch
        __classPrivateFieldSet(this, _EligibilityService_geoLocationFetchPromise, __classPrivateFieldGet(this, _EligibilityService_instances, "m", _EligibilityService_performGeoLocationFetch).call(this), "f");
        try {
            const location = await __classPrivateFieldGet(this, _EligibilityService_geoLocationFetchPromise, "f");
            return location;
        }
        finally {
            // Clear the promise after completion (success or failure)
            __classPrivateFieldSet(this, _EligibilityService_geoLocationFetchPromise, null, "f");
        }
    }
    /**
     * Check if user is eligible based on geo-blocked regions
     *
     * @param options - The eligibility check parameters.
     * @param options.blockedRegions - List of blocked region codes (e.g., ['US', 'CN']).
     * @returns True if eligible (not in blocked region), false otherwise.
     */
    async checkEligibility(options) {
        const { blockedRegions } = options;
        try {
            __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Checking eligibility', {
                blockedRegionsCount: blockedRegions.length,
            });
            // Returns UNKNOWN if we can't fetch the geo location
            const geoLocation = await this.fetchGeoLocation();
            // Only set to eligible if we have valid geolocation and it's not blocked
            if (geoLocation !== 'UNKNOWN') {
                const isEligible = blockedRegions.every((geoBlockedRegion) => !geoLocation
                    .toUpperCase()
                    .startsWith(geoBlockedRegion.toUpperCase()));
                __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Eligibility check completed', {
                    geoLocation,
                    isEligible,
                    blockedRegions,
                });
                return isEligible;
            }
            // Default to eligible if location is unknown
            return true;
        }
        catch (error) {
            __classPrivateFieldGet(this, _EligibilityService_deps, "f").logger.error(ensureError(error, 'EligibilityService.checkEligibility'), {
                tags: { feature: PERPS_CONSTANTS.FeatureName },
                context: {
                    name: 'EligibilityService.checkEligibility',
                    data: {},
                },
            });
            // Default to eligible on error
            return true;
        }
    }
    /**
     * Clear the geo-location cache
     * Useful for testing or forcing a fresh fetch
     */
    clearCache() {
        __classPrivateFieldSet(this, _EligibilityService_geoLocationCache, null, "f");
        __classPrivateFieldSet(this, _EligibilityService_geoLocationFetchPromise, null, "f");
        __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Cache cleared');
    }
}
_EligibilityService_geoCacheTtlMs = new WeakMap(), _EligibilityService_deps = new WeakMap(), _EligibilityService_geoLocationCache = new WeakMap(), _EligibilityService_geoLocationFetchPromise = new WeakMap(), _EligibilityService_instances = new WeakSet(), _EligibilityService_performGeoLocationFetch = 
/**
 * Perform the actual geo location fetch
 * Separated to allow proper promise management
 *
 * @returns The fetched geo location string, or 'UNKNOWN' on failure.
 */
async function _EligibilityService_performGeoLocationFetch() {
    let location = 'UNKNOWN';
    try {
        const environment = getEnvironment();
        __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Fetching geo location from API', {
            environment,
        });
        const response = await successfulFetch(ON_RAMP_GEO_BLOCKING_URLS[environment]);
        const textResult = await response?.text();
        location = textResult || 'UNKNOWN';
        // Cache the successful result
        __classPrivateFieldSet(this, _EligibilityService_geoLocationCache, {
            location,
            timestamp: Date.now(),
        }, "f");
        __classPrivateFieldGet(this, _EligibilityService_deps, "f").debugLogger.log('EligibilityService: Geo location fetched successfully', {
            location,
        });
        return location;
    }
    catch (error) {
        __classPrivateFieldGet(this, _EligibilityService_deps, "f").logger.error(ensureError(error, 'EligibilityService.performGeoLocationFetch'), {
            tags: { feature: PERPS_CONSTANTS.FeatureName },
            context: {
                name: 'EligibilityService.performGeoLocationFetch',
                data: {},
            },
        });
        // Don't cache failures
        return location;
    }
};
//# sourceMappingURL=EligibilityService.mjs.map