export default defineEventHandler(async (event) => {
  console.log('📊 Admin stats requested at:', new Date().toISOString());
  
  try {
    // Check if user is admin
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session || session.user.tier !== 'admin') {
      console.warn('🚨 Unauthorized admin stats access attempt');
      throw createError({
        statusCode: 403,
        statusMessage: 'Admin access required'
      });
    }
    
    console.log('✅ Admin access verified for user:', session.user.email);
    
    // Get real user count from Keycloak
    let userCount = 0;
    try {
      const { createKeycloakAdminClient } = await import('~/server/utils/keycloak-admin');
      const keycloakAdmin = createKeycloakAdminClient();
      userCount = await keycloakAdmin.getUserCount(false); // Exclude service accounts
      console.log('✅ Retrieved real user count from Keycloak:', userCount);
    } catch (keycloakError: any) {
      console.error('⚠️ Failed to get user count from Keycloak:', keycloakError);
      // Instead of returning mock data, return 0 or null to indicate data unavailable
      console.log('⚠️ User count unavailable, returning 0');
      userCount = 0;
    }
    
    // Return stats with real data
    const stats = {
      // Real user count from Keycloak (0 if unavailable)
      userCount: userCount,
      
      // Basic portal health
      portalStatus: 'online',
      lastUpdate: new Date().toISOString(),
      
      // Add flag to indicate if data is from cache or live
      dataSource: userCount > 0 ? 'live' : 'unavailable'
    };
    
    console.log('✅ Admin stats retrieved successfully:', stats);
    return stats;
    
  } catch (error: any) {
    console.error('❌ Admin stats error:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to retrieve admin statistics'
    });
  }
});
