import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { DOSSIER_TEMPLATE_ID } from '@red/domain';
import { DashboardStatsService } from '@services/dossier-templates/dashboard-stats.service';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { DossierTemplateStatsService } from '@services/entity-services/dossier-template-stats.service';
import { NGXLogger } from 'ngx-logger';
import { firstValueFrom } from 'rxjs';

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

        const dossierTemplate = inject(DossierTemplateStatsService).get(dossierTemplateId);
        if (!dossierTemplate) {
            await inject(Router).navigate([inject(TenantsService).activeTenantId, 'main', 'admin', 'dossier-templates']);
            return false;
        }
        return true;
    };
}

export function templateExistsWhenEnteringDossierList(): CanActivateFn {
    return async function (route: ActivatedRouteSnapshot) {
        const dossierTemplateId: string = route.paramMap.get(DOSSIER_TEMPLATE_ID);
        const dashboardStatsService = inject(DashboardStatsService);
        const dossierTemplatesService = inject(DossierTemplatesService);
        const logger = inject(NGXLogger);
        const router = inject(Router);
        const tenantsService = inject(TenantsService);

        await firstValueFrom(dashboardStatsService.loadAll());
        await firstValueFrom(dossierTemplatesService.loadAll());
        const dossierTemplateStats = dashboardStatsService.find(dossierTemplateId);
        if (!dossierTemplateStats || dossierTemplateStats.isEmpty) {
            logger.warn(`[ROUTES] Dossier template ${dossierTemplateId} not found, redirecting to main`);
            await router.navigate([tenantsService.activeTenantId, 'main']);
            return false;
        }
        return true;
    };
}
