import { AuthService } from './AuthService.js';

export class TokenRefreshManager {
    constructor(authInstance) {
        this.authInstance = authInstance;
        this.refreshInterval = null;
        this.isRefreshing = false;
        // Refresh every 50 minutes (tokens expire after 1 hour)
        this.REFRESH_INTERVAL_MS = 50 * 60 * 1000;
    }

    /**
     * Starts the automatic token refresh timer
     */
    startRefreshTimer() {
        console.log('[TokenRefreshManager] Starting automatic token refresh timer...');

        // Clear any existing timer
        this.stopRefreshTimer();

        this.refreshInterval = setInterval(async () => {
            await this.performRefresh();
        }, this.REFRESH_INTERVAL_MS);

        console.log(`[TokenRefreshManager] Timer set to refresh every ${this.REFRESH_INTERVAL_MS / 60000} minutes`);
    }

    /**
     * Stops the automatic token refresh timer
     */
    stopRefreshTimer() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
            console.log('[TokenRefreshManager] Token refresh timer stopped');
        }
    }

    /**
     * Performs a token refresh
     */
    async performRefresh() {
        if (this.isRefreshing) {
            console.log('[TokenRefreshManager] Refresh already in progress, skipping...');
            return;
        }

        // Only refresh if user is authenticated
        if (!this.authInstance || !this.authInstance.check()) {
            console.log('[TokenRefreshManager] User not authenticated, stopping refresh timer');
            this.stopRefreshTimer();
            return;
        }

        this.isRefreshing = true;

        try {
            console.log('[TokenRefreshManager] Performing scheduled token refresh...');

            const refreshResult = await AuthService.refreshToken(this.authInstance);

            if (refreshResult.success && refreshResult.token) {
                // Update the auth token silently
                this.authInstance.token(null, refreshResult.token, false);
                console.log('[TokenRefreshManager] Token refreshed successfully');
            } else {
                console.error('[TokenRefreshManager] Scheduled refresh failed:', refreshResult.error);

                // Stop the timer and logout on failure
                this.stopRefreshTimer();

                try {
                    // Dispatch logout event to stop other timers
                    window.dispatchEvent(new CustomEvent('auth-logout'));

                    await AuthService.logout();
                    this.authInstance.logout({
                        redirect: '/auth/login'
                    });
                } catch (logoutError) {
                    console.error('[TokenRefreshManager] Logout failed:', logoutError);
                    window.location.href = '/auth/login';
                }
            }
        } catch (error) {
            console.error('[TokenRefreshManager] Refresh error:', error);
            this.stopRefreshTimer();
        } finally {
            this.isRefreshing = false;
        }
    }

    /**
     * Manually triggers a token refresh
     * @returns {Promise<boolean>} Success status
     */
    async manualRefresh() {
        if (this.isRefreshing) {
            console.log('[TokenRefreshManager] Manual refresh requested but already in progress');
            return false;
        }

        await this.performRefresh();
        return true;
    }
}
