import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { findMenu } from '../services/menu.utils';
import { TenantService } from '../services/tenant.service';

export const hasMenuGuard = (menuCode: string): CanActivateFn => {
  return (_route, state) => {
    const tenantService = inject(TenantService);
    const router = inject(Router);

    const tenant = tenantService.tenant();

    if (!tenant) {
      return false;
    }

    const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;

    if (hasMenu || state.url === '/') {
      return true;
    }

    return router.createUrlTree(['/']);
  };
};
