/**
 * @file sparkTokenReader.js
 * @description Content script som läser Spark access_token från localStorage
 * 
 * Author: Linus Olofsson - Iver 
 * Date: 2026-02-24
 * 
 * @purpose Extrahera Spark Bearer token utan att öppna nya flikar
 * @invoked_by serviceWorker.js via chrome.tabs.sendMessage
 * @note Körs BARA på spark.iver.com — registrerad i manifest.json
 * @note Söker token i flera möjliga localStorage-format (direkt, OIDC Client, etc.)
 */

/**
 * Sök igenom localStorage efter Spark access token.
 * OIDC Client-bibliotek lagrar ofta tokens under nycklar som:
 *   "oidc.user:http://spark-authentication/auth:spark"
 * Medan enklare implementationer använder "access_token" direkt.
 */
function findSparkToken() {
    // Strategi 1: Direkt nyckel "access_token"
    const directToken = localStorage.getItem('access_token');
    if (directToken) {
        return {
            accessToken: directToken,
            expiresAt: localStorage.getItem('expires_at'),
            refreshToken: localStorage.getItem('refresh_token'),
            source: 'direct'
        };
    }

    // Strategi 2: OIDC Client-format "oidc.user:{authority}:{client_id}"
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith('oidc.user:')) {
            try {
                const data = JSON.parse(localStorage.getItem(key));
                if (data && data.access_token) {
                    return {
                        accessToken: data.access_token,
                        expiresAt: data.expires_at ? (data.expires_at * 1000).toString() : null,
                        refreshToken: data.refresh_token || null,
                        idToken: data.id_token || null,
                        profile: data.profile || null,
                        source: 'oidc.user',
                        key: key
                    };
                }
            } catch (e) {
                console.warn('Could not parse OIDC user data for key:', key, e);
            }
        }
    }

    // Strategi 3: Sök efter nycklar som innehåller "token" eller "auth"
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (!key) continue;
        const lowerKey = key.toLowerCase();
        
        if (lowerKey.includes('token') || lowerKey.includes('auth')) {
            const value = localStorage.getItem(key);
            // Kolla om värdet ser ut som en JWT (eyJ...)
            if (value && value.startsWith('eyJ')) {
                return {
                    accessToken: value,
                    expiresAt: null,
                    refreshToken: null,
                    source: 'search',
                    key: key
                };
            }
            // Kolla om det är JSON med access_token
            try {
                const parsed = JSON.parse(value);
                if (parsed && parsed.access_token) {
                    return {
                        accessToken: parsed.access_token,
                        expiresAt: parsed.expires_at ? String(parsed.expires_at) : null,
                        refreshToken: parsed.refresh_token || null,
                        source: 'search-json',
                        key: key
                    };
                }
            } catch (e) {
                // Inte JSON, ignorera
            }
        }
    }

    // Strategi 4: Dumpa alla nycklar (för debugging)
    const allKeys = [];
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        const value = localStorage.getItem(key);
        allKeys.push({ key, valueLength: value?.length || 0, preview: value?.substring(0, 50) });
    }
    
    return {
        accessToken: null,
        source: 'not_found',
        allKeys: allKeys
    };
}

// Lyssna på meddelanden från service worker
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'getSparkToken') {
        try {
            const result = findSparkToken();
            
            console.log(`[SparkTokenReader] Token found via: ${result.source}`, 
                result.accessToken ? `(${result.accessToken.substring(0, 20)}...)` : '(null)',
                result.key ? `key: ${result.key}` : '');

            let userInfo = null;
            if (result.profile) {
                userInfo = {
                    sub: result.profile.sub,
                    name: result.profile.name,
                    givenName: result.profile.given_name,
                    familyName: result.profile.family_name,
                    email: result.profile.email
                };
            }

            const expiresAt = result.expiresAt ? parseInt(result.expiresAt, 10) : null;

            sendResponse({
                success: !!result.accessToken,
                accessToken: result.accessToken || null,
                expiresAt: expiresAt,
                refreshToken: result.refreshToken || null,
                userInfo: userInfo,
                source: result.source,
                allKeys: result.allKeys || null
            });
        } catch (error) {
            console.error('[SparkTokenReader] Error:', error);
            sendResponse({
                success: false,
                error: error.message
            });
        }
        return true;
    }
});

// Meddela service worker att content script är redo
chrome.runtime.sendMessage({ action: 'sparkTokenReaderReady', url: window.location.href }).catch(() => {});
