/**
 * AsyncStorage Token Storage for React Native Mobile Platforms
 *
 * Bundler-agnostic AsyncStorage implementation for mobile platforms
 */
import AsyncStorage from '@react-native-async-storage/async-storage';
/**
 * Bundler-agnostic AsyncStorage wrapper
 * Handles different module resolution patterns across bundlers (Metro, Webpack, Rollup, etc.)
 */
class BundlerAgnosticAsyncStorage {
    constructor(asyncStorageModule) {
        // Try different import patterns to handle various bundlers
        if (asyncStorageModule?.default?.getItem) {
            // Metro/Webpack pattern: { default: { getItem, setItem, ... } }
            this.storage = asyncStorageModule.default;
        }
        else if (asyncStorageModule?.getItem) {
            // Direct export pattern: { getItem, setItem, ... }
            this.storage = asyncStorageModule;
        }
        else if (typeof asyncStorageModule === 'function') {
            // Function export pattern (some bundlers)
            this.storage = asyncStorageModule();
        }
        else {
            // Log the structure for debugging
            console.error('[BundlerAgnosticAsyncStorage] Unknown AsyncStorage structure:', asyncStorageModule);
            throw new Error('AsyncStorage methods not found. Expected structure with getItem/setItem methods. ' +
                'Make sure @react-native-async-storage/async-storage is properly installed.');
        }
        // Validate that we have the required methods
        const requiredMethods = ['getItem', 'setItem', 'removeItem', 'getAllKeys', 'multiRemove'];
        const missingMethods = requiredMethods.filter(method => typeof this.storage[method] !== 'function');
        if (missingMethods.length > 0) {
            throw new Error(`AsyncStorage missing required methods: ${missingMethods.join(', ')}. ` +
                'Ensure @react-native-async-storage/async-storage is properly installed and compatible.');
        }
    }
    async getItem(key) {
        return this.storage.getItem(key);
    }
    async setItem(key, value) {
        return this.storage.setItem(key, value);
    }
    async removeItem(key) {
        return this.storage.removeItem(key);
    }
    async getAllKeys() {
        return this.storage.getAllKeys();
    }
    async multiRemove(keys) {
        return this.storage.multiRemove(keys);
    }
}
/**
 * AsyncStorage implementation for mobile platforms
 *
 * This class is only used on mobile platforms (iOS/Android).
 * Web platforms use LocalStorageTokenStorage from core SDK.
 */
export class AsyncStorageTokenStorage {
    constructor(keyPrefix = 'pers_tokens_') {
        this.keyPrefix = keyPrefix;
        try {
            // Initialize bundler-agnostic AsyncStorage wrapper
            this.asyncStorage = new BundlerAgnosticAsyncStorage(AsyncStorage);
        }
        catch (error) {
            console.error('[AsyncStorageTokenStorage] Failed to initialize:', error);
            throw new Error('Failed to initialize AsyncStorage. Make sure @react-native-async-storage/async-storage is installed and ' +
                'this code is running on a React Native mobile platform (not web).');
        }
    }
    async set(key, value) {
        try {
            const fullKey = `${this.keyPrefix}${key}`;
            await this.asyncStorage.setItem(fullKey, value);
            console.log(`[AsyncStorage] Token stored: ${key}`);
        }
        catch (error) {
            console.error(`[AsyncStorage] Failed to store token ${key}:`, error);
            throw new Error(`Token storage failed: ${error}`);
        }
    }
    async get(key) {
        try {
            const fullKey = `${this.keyPrefix}${key}`;
            const value = await this.asyncStorage.getItem(fullKey);
            console.log(`[AsyncStorage] Token retrieved: ${key} - ${value ? 'exists' : 'null'}`);
            return value;
        }
        catch (error) {
            console.error(`[AsyncStorage] Failed to retrieve token ${key}:`, error);
            return null;
        }
    }
    async remove(key) {
        try {
            await this.asyncStorage.removeItem(`${this.keyPrefix}${key}`);
        }
        catch (error) {
            console.error(`Failed to remove token ${key}:`, error);
        }
    }
    async clear() {
        try {
            const allKeys = await this.asyncStorage.getAllKeys();
            const ourKeys = allKeys.filter(key => key.startsWith(this.keyPrefix));
            if (ourKeys.length > 0) {
                console.log(`[AsyncStorage] Clearing ${ourKeys.length} token(s):`, ourKeys);
                await this.asyncStorage.multiRemove(ourKeys);
                console.log('[AsyncStorage] All tokens cleared successfully');
            }
            else {
                console.log('[AsyncStorage] No tokens to clear');
            }
        }
        catch (error) {
            console.error('[AsyncStorage] Failed to clear token storage:', error);
        }
    }
}
