import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { logger } from '@isa/core/logging';

export const hasTabIdGuard: CanActivateFn = (route) => {
  const router = inject(Router);
  const log = logger(() => ({
    context: 'hasTabIdGuard',
    url: route.url.map((s) => s.path).join('/'),
    params: JSON.stringify(route.params),
    queryParams: JSON.stringify(route.queryParams),
  }));
  const tabId = route.params['tabId'];
  const isValidTabId = tabId && !isNaN(parseInt(tabId)) && parseInt(tabId) > 0;

  if (isValidTabId) {
    log.debug('Valid tabId - allowing navigation', () => ({
      tabId,
      parsedValue: parseInt(tabId),
    }));
    return true;
  }

  log.warn('Invalid or missing tabId - redirecting to dashboard', () => ({
    tabId,
    isNaN: isNaN(parseInt(tabId)),
    parsedValue: parseInt(tabId),
    redirectTo: '/kunde/dashboard',
  }));
  return router.parseUrl('/kunde/dashboard');
};
