import { Router } from '@angular/router';
import { inject, Injector, ProviderToken } from '@angular/core';
import { DossiersService } from '../dossiers/dossiers.service';

/** Usage in components or services is only allowed in guards or in constructors.
 * Otherwise, it causes errors on navigation to other screens if the component is reused. */
export const dossiersServiceResolver = (injector = inject(Injector), router = inject(Router)) => {
    let route = router.routerState.root;
    while (route.firstChild) {
        route = route.firstChild;
    }
    const token: ProviderToken<DossiersService> = route.snapshot.data.dossiersService;
    return injector.get<DossiersService>(token);
};

export const dossiersServiceProvider = {
    provide: DossiersService,
    useFactory: dossiersServiceResolver,
    deps: [Injector, Router],
};
