/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import { debugLogger } from '../utils/debugLogger.js';
const SIXTH_DIR = path.join(os.homedir(), '.sixth');
const USER_CACHE_FILE = path.join(SIXTH_DIR, 'user.json');
export class SixthUserCache {
    /**
     * Check if user is authenticated (has cached user info) - FAST synchronous check first
     */
    static async isUserAuthenticated() {
        try {
            // Fast synchronous check first
            const syncExists = await this.isUserCacheFileExists();
            if (!syncExists)
                return false;
            const userInfo = await this.getUserInfo();
            return userInfo !== null;
        }
        catch {
            return false;
        }
    }
    /**
     * Fast synchronous check if cache file exists
     */
    static async isUserCacheFileExists() {
        try {
            await fs.access(USER_CACHE_FILE);
            return true;
        }
        catch {
            return false;
        }
    }
    /**
     * Get cached user info
     */
    static async getUserInfo() {
        try {
            const data = await fs.readFile(USER_CACHE_FILE, 'utf8');
            const userInfo = JSON.parse(data);
            // Validate the required fields
            if (userInfo.id && userInfo.email && userInfo.fullname) {
                return userInfo;
            }
            // Invalid data, remove it
            await this.clearUserInfo();
            return null;
        }
        catch (error) {
            debugLogger.error('Failed to read user cache:', error);
            return null;
        }
    }
    /**
     * Cache user info
     */
    static async cacheUserInfo(userInfo) {
        try {
            // Ensure directory exists
            await fs.mkdir(SIXTH_DIR, { recursive: true });
            // Write user info
            await fs.writeFile(USER_CACHE_FILE, JSON.stringify(userInfo, null, 2), 'utf8');
            debugLogger.log('User info cached successfully');
        }
        catch (error) {
            debugLogger.error('Failed to cache user info:', error);
            throw new Error('Failed to save user information');
        }
    }
    /**
     * Clear cached user info
     */
    static async clearUserInfo() {
        try {
            await fs.unlink(USER_CACHE_FILE);
            debugLogger.log('User cache cleared');
        }
        catch (error) {
            // File might not exist, which is fine
            debugLogger.log('User cache was already clear');
        }
    }
    /**
     * Get user's subscription status
     */
    static async isUserSubscriber() {
        const userInfo = await this.getUserInfo();
        return userInfo?.subscriber ?? false;
    }
    /**
     * Background validation - validate cached token with server (non-blocking)
     */
    static validateInBackground() {
        // Run validation in background without blocking startup
        setImmediate(async () => {
            try {
                const userInfo = await this.getUserInfo();
                if (!userInfo)
                    return;
                // Validate with server in background
                // This could be expanded to actually validate the token
                debugLogger.log('Background auth validation completed');
            }
            catch (error) {
                debugLogger.warn('Background auth validation failed:', error);
            }
        });
    }
}
//# sourceMappingURL=sixthUserCache.js.map