/**
 * Hook for filtering routes based on subscription features
 */

import { useMemo } from 'react';
import { RouteConfig } from '../router/routes.config';
import { useSubscription } from '../api/hooks/subscription';
import { useCurrentTenant } from '../stores';
import { usePremises } from '../api/hooks/usePremises';

export const useSubscriptionAwareRoutes = (routes: RouteConfig[]) => {
  const { subscriptionInfo, canAccessAnalytics } = useSubscription();
  const currentTenant = useCurrentTenant();

  // Check if tenant has child tenants (only for enterprise tier)
  const isEnterprise = subscriptionInfo.plan === 'enterprise';
  const { data: childTenants = [] } = usePremises(
    currentTenant?.id || '',
    {},
    { enabled: isEnterprise && !!currentTenant?.id }
  );
  const hasChildTenants = childTenants.length > 0;

  const filteredRoutes = useMemo(() => {
    const filterRoutesBySubscription = (routeList: RouteConfig[]): RouteConfig[] => {
      return routeList.reduce((filtered, route) => {
        // Check if route requires subscription features
        if (route.requiredSubscriptionFeature) {
          // Special case for multi_tenant_management which requires enterprise AND child tenants
          if (route.requiredSubscriptionFeature === 'multi_tenant_management') {
            if (!isEnterprise || !hasChildTenants) {
              return filtered; // Skip this route if not enterprise or no child tenants
            }
          }
          // Special case for distribution feature which requires enterprise
          else if (route.requiredSubscriptionFeature === 'distribution') {
            if (!isEnterprise) {
              return filtered; // Skip this route
            }
          }
        }

        if (route.requiredAnalyticsLevel) {
          const hasAccess = canAccessAnalytics(route.requiredAnalyticsLevel);
          if (!hasAccess) {
            return filtered; // Skip this route
          }
        }

        // Handle specific analytics routes
        if (route.path === '/app/analytics') {
          // Only show analytics if user has at least basic access
          if (!canAccessAnalytics('basic')) {
            return filtered; // Skip analytics entirely
          }
        }

        // Filter children recursively
        const filteredRoute = {
          ...route,
          children: route.children ? filterRoutesBySubscription(route.children) : route.children
        };

        // Only include parent if it has accessible children or is accessible itself
        if (route.children) {
          if (filteredRoute.children && filteredRoute.children.length > 0) {
            filtered.push(filteredRoute);
          } else if (!route.requiredAnalyticsLevel && !route.requiredSubscriptionFeature) {
            // Include parent without children if it doesn't require subscription
            filtered.push({ ...route, children: [] });
          }
        } else {
          filtered.push(filteredRoute);
        }

        return filtered;
      }, [] as RouteConfig[]);
    };

    if (subscriptionInfo.loading) {
      // While loading, show basic routes only
      return routes.filter(route =>
        !route.requiredAnalyticsLevel &&
        !route.requiredSubscriptionFeature &&
        route.path !== '/app/analytics'
      );
    }

    return filterRoutesBySubscription(routes);
  }, [routes, subscriptionInfo, canAccessAnalytics, isEnterprise, hasChildTenants]);

  return {
    filteredRoutes,
    subscriptionInfo,
    isLoading: subscriptionInfo.loading
  };
};
