// server/api/admin/users.get.ts

export default defineEventHandler(async (event) => {
  try {
    const { createKeycloakAdminClient } = await import('~/server/utils/keycloak-admin');
    const { determineMemberTierFromKeycloak } = await import('~/server/utils/member-tiers');
    
    // Initialize Keycloak admin client
    const keycloakAdmin = createKeycloakAdminClient();
    
    // Get all users from Keycloak
    const keycloakUsers = await keycloakAdmin.getUsers();
    
    // Filter out service accounts and transform the data
    const users = keycloakUsers
      .filter((user: any) => !user.username?.startsWith('service-account-'))
      .map((user: any) => {
        // Determine tier/role from groups
        const tierResult = determineMemberTierFromKeycloak(user);
        
        return {
          id: user.id,
          username: user.username,
          email: user.email,
          firstName: user.firstName,
          lastName: user.lastName,
          enabled: user.enabled,
          emailVerified: user.emailVerified,
          createdTimestamp: user.createdTimestamp,
          groups: user.groups || [],
          tier: tierResult.tier,
          tierSource: tierResult.source,
          tierConfidence: tierResult.confidence,
          // Note: Keycloak doesn't track last login by default
          // This would need to be implemented via events or custom attributes
          lastLogin: user.attributes?.lastLogin?.[0] || null
        };
      });
    
    console.log(`[API] Retrieved ${users.length} users from Keycloak`);
    
    return {
      success: true,
      data: {
        users,
        total: users.length,
        dataSource: 'keycloak'
      }
    };
  } catch (error: any) {
    console.error('[API] Error fetching users:', error);
    
    // Return empty list on error instead of throwing
    return {
      success: false,
      data: {
        users: [],
        total: 0,
        dataSource: 'unavailable',
        error: error.message
      }
    };
  }
});