/**
 * Admin Authentication Module
 * Handles user authentication, session management, and admin authorization
 */

// Check if user is authenticated as admin
async function checkAdminAuth() {
    try {
        const response = await fetch('/api/auth/check');
        const data = await response.json();
        
        console.log('Admin auth check result:', data);
        
        if (!data.authenticated || !data.user?.isAdmin) {
            console.log('Redirecting to login - not authenticated or not admin');
            window.location.href = '/login.html';
            return;
        }
        
        console.log('User is authenticated as admin:', data.user);
        
        // Display admin info (desktop)
        const adminInfoEl = document.getElementById('admin-info');
        if (adminInfoEl) {
            adminInfoEl.innerHTML = `
                <span>👤 ${window.adminCore.escapeHtml(data.user.email)}</span>
                <button id="logout-btn" class="btn btn-secondary btn-sm">Logout</button>
            `;
            
            // Add logout event listener
            const logoutBtn = document.getElementById('logout-btn');
            if (logoutBtn) {
                logoutBtn.addEventListener('click', handleLogout);
            }
        }
        
        // Display admin info (mobile)
        const mobileAdminInfo = document.getElementById('mobile-admin-info');
        if (mobileAdminInfo) {
            mobileAdminInfo.innerHTML = `
                <div>👤 ${window.adminCore.escapeHtml(data.user.email)}</div>
                <button id="mobile-logout-btn" class="btn btn-secondary btn-sm" style="margin-top: 10px; width: 100%;">Logout</button>
            `;
            
            // Add logout listener for mobile button
            const mobileLogoutBtn = document.getElementById('mobile-logout-btn');
            if (mobileLogoutBtn) {
                mobileLogoutBtn.addEventListener('click', handleLogout);
            }
        }
        
    } catch (error) {
        console.error('Auth check failed:', error);
        window.location.href = '/login.html';
    }
}

// Handle logout
async function handleLogout() {
    if (!confirm('Are you sure you want to logout?')) {
        return;
    }
    
    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            window.location.href = '/login.html';
        } else {
            window.adminCore.showStatus('Logout failed. Please try again.', 'error');
        }
    } catch (error) {
        console.error('Logout error:', error);
        window.adminCore.showStatus('Logout failed. Please try again.', 'error');
    }
}

// Export authentication functions
window.adminAuth = {
    checkAdminAuth,
    handleLogout
};
