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

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

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

  const filteredRoutes = useMemo(() => {
    const filterRoutesBySubscription = (routeList: RouteConfig[]): RouteConfig[] => {
      return routeList.reduce((filtered, route) => {
        // Check if route requires subscription features
        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) {
            // 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.path !== '/app/analytics'
      );
    }

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

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