import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router';
import { WatermarksMapService } from '@services/entity-services/watermarks-map.service';
import { DOSSIER_TEMPLATE_ID, WATERMARK_ID } from '@red/domain';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

export function watermarkExistsGuard(): CanActivateFn {
    return async function (route: ActivatedRouteSnapshot) {
        const dossierTemplateId = route.parent.paramMap.get(DOSSIER_TEMPLATE_ID);
        const watermarkId = Number(route.paramMap.get(WATERMARK_ID));

        if (inject(WatermarksMapService).get(dossierTemplateId, watermarkId)) {
            return true;
        }

        await inject(Router).navigate([
            inject(TenantsService).activeTenantId,
            'main',
            'admin',
            'dossier-templates',
            dossierTemplateId,
            'watermarks',
        ]);
        return false;
    };
}
