/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Dynamic import for open package
import { SIXTH_AUTH_CONFIG } from './sixthAuth.js';
import { SixthAuthServer } from './sixthAuthServer.js';
import { SixthUserCache } from './sixthUserCache.js';
import { debugLogger } from '../utils/debugLogger.js';
export class SixthAuthFlow {
    authServer;
    constructor() {
        this.authServer = new SixthAuthServer(SIXTH_AUTH_CONFIG);
    }
    /**
     * Check if user is authenticated (fast cache check + background validation)
     */
    async isUserAuthenticated() {
        const isAuthenticated = await SixthUserCache.isUserAuthenticated();
        // If authenticated, start background validation but don't wait for it
        if (isAuthenticated) {
            SixthUserCache.validateInBackground();
        }
        return isAuthenticated;
    }
    /**
     * Get cached user info if available
     */
    async getUserInfo() {
        return SixthUserCache.getUserInfo();
    }
    /**
     * Start the authentication flow
     */
    async startAuthFlow() {
        try {
            debugLogger.log('Starting Sixth authentication flow');
            // Start the callback server first
            const authPromise = this.authServer.startAndWaitForAuth();
            // Get the callback URL
            const callbackUrl = this.authServer.getCallbackUrl();
            // Construct the authentication URL
            const authUrl = this.buildAuthUrl(callbackUrl);
            debugLogger.log(`Opening browser for authentication: ${authUrl}`);
            // Open the browser (using dynamic import for ESM compatibility)
            const { default: open } = await import('open');
            await open(authUrl);
            // Wait for authentication to complete
            const userInfo = await authPromise;
            debugLogger.log('Authentication completed successfully');
            return userInfo;
        }
        catch (error) {
            debugLogger.error('Authentication flow failed:', error);
            this.authServer.stop();
            throw error;
        }
    }
    /**
     * Build the authentication URL
     */
    buildAuthUrl(callbackUrl) {
        const params = new URLSearchParams({
            callback: callbackUrl,
            referrer: 'cli',
        });
        return `${SIXTH_AUTH_CONFIG.webUrl}?${params.toString()}`;
    }
    /**
     * Logout user by clearing cached info
     */
    async logout() {
        await SixthUserCache.clearUserInfo();
        debugLogger.log('User logged out');
    }
    /**
     * Get user subscription status
     */
    async isUserSubscriber() {
        return SixthUserCache.isUserSubscriber();
    }
    /**
     * Refresh user info from API
     */
    async refreshUserInfo() {
        const currentUser = await this.getUserInfo();
        if (!currentUser) {
            return null;
        }
        try {
            // This would require the current token, which we don't store for security
            // For now, return the cached info
            // In a real implementation, you might want to store a refresh token
            return currentUser;
        }
        catch (error) {
            debugLogger.error('Failed to refresh user info:', error);
            return currentUser;
        }
    }
    /**
     * Stop any running auth servers
     */
    stop() {
        this.authServer.stop();
    }
}
//# sourceMappingURL=sixthAuthFlow.js.map