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

export const useUnifiedAuth = () => {
  // Get both auth systems
  const directusAuth = useDirectusAuth();
  const directusUser = useDirectusUser();
  const customAuth = useCustomAuth();
  
  // Create unified user object
  const user = computed<UnifiedUser | null>(() => {
    // Check custom Keycloak auth first
    if (customAuth.authenticated?.value && customAuth.user?.value) {
      const keycloakUser = customAuth.user.value as any; // Type cast for flexibility
      
      // Construct name from available fields
      let name = keycloakUser.name || keycloakUser.username || keycloakUser.email || 'User';
      
      return {
        id: keycloakUser.id || 'unknown',
        email: keycloakUser.email || '',
        name: name,
        tier: 'basic', // Could be enhanced with Keycloak attributes
        authSource: 'keycloak',
        raw: keycloakUser
      };
    }
    
    // Fall back to Directus user
    if (directusUser.value && directusUser.value.email) {
      return {
        id: directusUser.value.id,
        email: directusUser.value.email,
        name: `${directusUser.value.first_name || ''} ${directusUser.value.last_name || ''}`.trim() || directusUser.value.email,
        tier: directusUser.value.tier || 'basic',
        authSource: 'directus',
        raw: directusUser.value
      };
    }
    
    return null;
  });
  
  // Unified logout function
  const logout = async () => {
    if (user.value?.authSource === 'keycloak') {
      // Custom Keycloak logout
      await customAuth.logout();
    } else if (user.value?.authSource === 'directus') {
      // Directus logout
      await directusAuth.logout();
      await navigateTo('/login');
    }
  };
  
  // Check if user is authenticated
  const isAuthenticated = computed(() => !!user.value);
  
  // Get auth source
  const authSource = computed(() => user.value?.authSource);
  
  // Check if user has specific tier
  const hasTier = (tier: string) => {
    return user.value?.tier === tier;
  };
  
  // Check if user is admin
  const isAdmin = computed(() => hasTier('admin'));
  
  return {
    user: readonly(user),
    logout,
    isAuthenticated: readonly(isAuthenticated),
    authSource: readonly(authSource),
    hasTier,
    isAdmin: readonly(isAdmin),
  };
};
