export interface UnifiedUser {
  id: string;
  email: string;
  name: string;
  username: string;
  tier?: string;
  authSource: 'keycloak';
  raw: any;
}

export const useUnifiedAuth = () => {
  // Get Keycloak auth
  const customAuth = useCustomAuth();
  
  // Create unified user object from Keycloak only
  const user = computed<UnifiedUser | null>(() => {
    if (customAuth.authenticated?.value && customAuth.user?.value) {
      const keycloakUser = customAuth.user.value as any;
      
      return {
        id: keycloakUser.id,
        email: keycloakUser.email || '',
        username: keycloakUser.username || keycloakUser.email || '',
        name: keycloakUser.name || keycloakUser.username || keycloakUser.email || 'User',
        tier: 'basic', // Could be enhanced with Keycloak attributes/roles
        authSource: 'keycloak',
        raw: keycloakUser
      };
    }
    
    return null;
  });
  
  // Unified logout function (Keycloak only)
  const logout = async () => {
    console.log('[UNIFIED_AUTH] Logging out user');
    await customAuth.logout();
  };
  
  // Check if user is authenticated
  const isAuthenticated = computed(() => !!user.value);
  
  // Get auth source (always Keycloak now)
  const authSource = computed(() => user.value?.authSource || 'keycloak');
  
  // Check if user has specific tier
  const hasTier = (tier: string) => {
    return user.value?.tier === tier;
  };
  
  // Check if user is admin (could be enhanced with Keycloak roles)
  const isAdmin = computed(() => hasTier('admin'));
  
  return {
    user: readonly(user),
    logout,
    isAuthenticated: readonly(isAuthenticated),
    authSource: readonly(authSource),
    hasTier,
    isAdmin: readonly(isAdmin),
  };
};
