import { ResolveFn } from '@angular/router';
import { TabService } from './tab';
import { Tab } from './schemas';
import { inject } from '@angular/core';
import { logger } from '@isa/core/logging';
import { getNextTabNameHelper } from './helpers';

export const tabResolverFn: ResolveFn<Tab> = (route) => {
  const log = logger(() => ({
    context: 'tabResolverFn',
    url: route.url.map((s) => s.path).join('/'),
    params: JSON.stringify(route.params),
    queryParams: JSON.stringify(route.queryParams),
  }));
  const tabId = parseInt(route.params['tabId']);
  const tabService = inject(TabService);

  if (!tabId || isNaN(tabId) || Number.MAX_SAFE_INTEGER < tabId) {
    log.error('Invalid tabId', { tabId });
    throw new Error('Invalid tabId');
  }

  let tab = tabService.entityMap()[tabId];

  if (!tab) {
    const tabName = getNextTabNameHelper(tabService.entityMap());
    tab = tabService.addTab({
      id: tabId,
      name: tabName,
      metadata: {
        process_type: 'cart',
      },
    });
  }

  tabService.activateTab(tab.id);

  return tab;
};

/// @deprecated use tabResolverFn instead
export const processResolverFn: ResolveFn<Tab> = async (route) => {
  const tabService = inject(TabService);
  await new Promise((resolve) => setTimeout(resolve, 0));
  const id = parseInt(route.params['tabId']);
  return tabService.entityMap()[id];
};
