import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { ArchivedDossiersService } from '@services/dossiers/archived-dossiers.service';
import { DOSSIER_TEMPLATE_ID } from '@red/domain';
import { DashboardStatsService } from '@services/dossier-templates/dashboard-stats.service';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { NGXLogger } from 'ngx-logger';
import { ACTIVE_DOSSIERS_SERVICE, ARCHIVED_DOSSIERS_SERVICE } from '../tokens';

export function loadAllDossiersGuard(): CanActivateFn {
    return async () => {
        const logger = inject(NGXLogger);
        logger.info('[GUARDS] loadAllDossiersGuard start');

        const services = [inject(ArchivedDossiersService), inject(ActiveDossiersService)];
        const requests = services.map(service => firstValueFrom(service.loadAll()));
        await Promise.all(requests);

        logger.info('[GUARDS] loadAllDossiersGuard end');
        return true;
    };
}

export function loadActiveDossiersGuard(): CanActivateFn {
    return async () => {
        const logger = inject(NGXLogger);
        logger.info('[GUARDS] loadDossiersGuard start');

        await firstValueFrom(inject<ActiveDossiersService>(ACTIVE_DOSSIERS_SERVICE).loadAll());

        logger.info('[GUARDS] loadDossiersGuard end');
        return true;
    };
}

export function loadArchivedDossiersGuard(): CanActivateFn {
    return async (route: ActivatedRouteSnapshot) => {
        const logger = inject(NGXLogger);
        logger.info('[GUARDS] loadArchivedDossiersGuard start');

        const dossiersService = inject<ArchivedDossiersService>(ARCHIVED_DOSSIERS_SERVICE);
        const dossierTemplateId = route.paramMap.get(DOSSIER_TEMPLATE_ID);
        const dossierTemplateStats = inject(DashboardStatsService).find(dossierTemplateId);

        if (dossierTemplateStats?.numberOfArchivedDossiers === 0) {
            logger.info('[GUARDS] loadArchivedDossiersGuard no archived dossiers, redirect to active dossiers page');
            await inject(Router).navigate([inject(TenantsService).activeTenantId, 'main', dossierTemplateId, 'dossiers']);
            return false;
        }

        await firstValueFrom(dossiersService.loadAll());
        logger.info('[GUARDS] loadArchivedDossiersGuard end');
        return true;
    };
}
