import { inject, Injectable } from '@angular/core';
import { CanActivate, CanActivateFn } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { TrashService } from '@services/entity-services/trash.service';
import { SystemPreferencesService } from '@services/system-preferences.service';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { ACTIVE_DOSSIERS_SERVICE } from '../tokens';

@Injectable({ providedIn: 'root' })
export class TrashGuard implements CanActivate {
    constructor(
        private readonly _trashService: TrashService,
        private readonly _systemPreferences: SystemPreferencesService,
        private readonly _activeDossierService: ActiveDossiersService,
    ) {}

    async canActivate(): Promise<boolean> {
        await this._systemPreferences.loadPreferencesIfNeeded();
        await firstValueFrom(this._activeDossierService.loadAll());
        await firstValueFrom(this._trashService.loadAll());
        return true;
    }
}

export function trashGuard(): CanActivateFn {
    return async () => {
        await inject(SystemPreferencesService).loadPreferencesIfNeeded();
        await firstValueFrom(inject<ActiveDossiersService>(ACTIVE_DOSSIERS_SERVICE).loadAll());
        await firstValueFrom(inject(TrashService).loadAll());
        return true;
    };
}
