export default defineEventHandler(async (event) => {
  console.log('🔍 Session check requested at:', new Date().toISOString());
  
  try {
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    
    console.log('🍪 Cookie header present:', !!cookieHeader);
    console.log('🍪 Cookie header length:', cookieHeader?.length || 0);
    
    const session = sessionManager.getSession(cookieHeader);

    if (!session) {
      console.log('❌ No valid session found');
      return {
        authenticated: false,
        user: null,
        groups: [],
        member: null
      };
    }

    console.log('✅ Valid session found for user:', session.user.email);
    console.log('🎯 User tier:', session.user.tier);
    console.log('📋 User groups:', session.user.groups);
    console.log('👤 User data:', {
      id: session.user.id,
      email: session.user.email,
      name: session.user.name,
      firstName: session.user.firstName,
      lastName: session.user.lastName,
      username: session.user.username
    });

    // Fetch complete member data from database
    let memberData = null;
    try {
      console.log('🔍 Fetching member data for Keycloak ID:', session.user.id);
      const { getMemberByKeycloakId } = await import('~/server/utils/nocodb');
      memberData = await getMemberByKeycloakId(session.user.id);
      
      if (memberData) {
        console.log('✅ Member data found:', {
          memberId: memberData.member_id,
          email: memberData.email,
          name: `${memberData.first_name} ${memberData.last_name}`,
          duesStatus: memberData.current_year_dues_paid
        });
      } else {
        console.log('⚠️ No member record found for Keycloak ID:', session.user.id);
      }
    } catch (memberError) {
      console.error('❌ Failed to fetch member data:', memberError);
      // Continue without member data - user can still access basic features
    }

    return {
      success: true,
      authenticated: true,
      user: session.user,
      groups: session.user.groups || [],
      member: memberData
    };
  } catch (error) {
    console.error('❌ Session check error:', error);
    return {
      authenticated: false,
      user: null,
      groups: [],
      member: null
    };
  }
});
