import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router';
import { DOSSIER_TEMPLATE_ID, ENTITY_TYPE } from '@red/domain';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

export function entityExistsGuard(): CanActivateFn {
    return async function (route: ActivatedRouteSnapshot): Promise<boolean> {
        const dossierTemplateId = route.paramMap.get(DOSSIER_TEMPLATE_ID);
        const type = route.paramMap.get(ENTITY_TYPE);

        if (!inject(DictionariesMapService).get(dossierTemplateId, type)) {
            const dossierTemplate = inject(DossierTemplatesService).find(dossierTemplateId);
            await inject(Router).navigate([`/${inject(TenantsService).activeTenantId}/${dossierTemplate.routerLink}/entities`]);
            return false;
        }

        return true;
    };
}
