/**
 * License Validation Service
 * Handles license validation for the jaak-visage webcomponent
 */
export class LicenseValidationService {
    apiEndpoint = '/api/v1/license/validate';
    baseUrl;
    // Environment-specific base URLs
    static ENVIRONMENT_URLS = {
        dev: 'https://api.dev.jaak.ai',
        qa: 'https://api.qa.jaak.ai',
        sandbox: 'https://api.sandbox.jaak.ai',
        prod: 'https://services.api.jaak.ai',
    };
    constructor(environment = 'prod') {
        this.baseUrl = LicenseValidationService.ENVIRONMENT_URLS[environment];
    }
    /**
     * Validate license with the API
     * @param license License key to validate
     * @param traceId Optional trace ID from W3C Trace Context
     * @param appId Optional application ID
     * @param metadata Optional additional metadata
     * @returns Promise<LicenseValidationResponse>
     */
    async validateLicense(license, traceId, appId = 'jaak-visage-web') {
        // Generate traceId if not provided
        const effectiveTraceId = traceId || this.generateTraceId();
        // Build request body
        const requestBody = {
            license: traceId ? `L${effectiveTraceId}` : license,
            origin: 'web',
            app_id: appId,
            product: 'kyc',
            metadata: {
                sdk_version: '1.0.0',
            },
        };
        const headers = {
            'Content-Type': 'application/json',
        };
        // Add traceparent header with the effective traceId
        headers['traceparent'] = `00-${effectiveTraceId}-${this.generateSpanId()}-01`;
        try {
            const response = await fetch(`${this.baseUrl}${this.apiEndpoint}`, {
                method: 'POST',
                headers,
                body: JSON.stringify(requestBody),
            });
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw {
                    error: errorData.error || 'license_validation_failed',
                    error_description: errorData.error_description || `HTTP ${response.status}: ${response.statusText}`,
                    status_code: response.status,
                };
            }
            const responseData = await response.json();
            // Add the traceId to the response
            return {
                ...responseData,
                traceId: effectiveTraceId,
            };
        }
        catch (error) {
            if (error.error) {
                throw error;
            }
            throw {
                error: 'network_error',
                error_description: 'Failed to connect to license validation service',
                status_code: 0,
            };
        }
    }
    /**
     * Generate a random trace ID for W3C Trace Context (32 hex characters)
     */
    generateTraceId() {
        const array = new Uint8Array(16);
        crypto.getRandomValues(array);
        return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
    }
    /**
     * Generate a random span ID for W3C Trace Context (16 hex characters)
     */
    generateSpanId() {
        const array = new Uint8Array(8);
        crypto.getRandomValues(array);
        return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
    }
    /**
     * Extract trace ID from license field
     * License format: "L<32-hex-chars>"
     * Example: "Ld79223833a2fd91971e4c14a33298904" -> "d79223833a2fd91971e4c14a33298904"
     */
    static extractTraceIdFromLicense(license) {
        if (!license || typeof license !== 'string') {
            return null;
        }
        // Remove "L" prefix if present
        const traceId = license.startsWith('L') ? license.slice(1) : license;
        // Validate format (32 hex characters)
        if (traceId.length === 32 && /^[a-f0-9]{32}$/i.test(traceId)) {
            return traceId.toLowerCase();
        }
        console.warn('[LicenseValidationService] Invalid license format for trace ID:', license);
        return null;
    }
}
//# sourceMappingURL=LicenseValidationService.js.map
