import { inject, Injectable } from '@angular/core';
import { ARCHIVE_ROUTE, Dossier, DOSSIERS_ARCHIVE, DOSSIERS_ROUTE } from '@red/domain';
import { catchError, switchMap, tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { ActiveDossiersService } from './active-dossiers.service';
import { DossiersService } from './dossiers.service';
import { FilesMapService } from '../files/files-map.service';
import { FeaturesService } from '../features.service';
import { Router } from '@angular/router';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

@Injectable({ providedIn: 'root' })
export class ArchivedDossiersService extends DossiersService {
    readonly #activeDossiersService = inject(ActiveDossiersService);
    readonly #filesMapService = inject(FilesMapService);
    readonly #featuresService = inject(FeaturesService);
    readonly #tenantsService = inject(TenantsService);
    readonly #router = inject(Router);
    protected readonly _defaultModelPath = 'archived-dossiers';
    readonly routerPath = ARCHIVE_ROUTE;

    archive(dossiers: Dossier[]): Observable<unknown> {
        const showArchiveFailedToast = () => {
            this._toaster.error(_('dossier-listing.archive.archive-failed'), {
                params: {
                    dossierName: dossiers.map(d => d.dossierName).join(', '),
                },
            });
            return of({});
        };

        const archivedDossiersIds = dossiers.map(d => d.dossierId);
        const dossierTemplateId = dossiers[0].dossierTemplateId;

        return this._post(archivedDossiersIds, `${this._defaultModelPath}/archive`).pipe(
            switchMap(() => this._dashboardStatsService.loadAll()),
            tap(() => this.#removeFromActiveDossiers(archivedDossiersIds)),
            switchMap(async () => {
                let route = dossiers[0].dossiersListRouterLink;
                if (!this.#activeDossiersService.all.find(d => d.dossierTemplateId === dossierTemplateId)) {
                    route = route.replace(DOSSIERS_ROUTE, ARCHIVE_ROUTE);
                }
                await this.#router.navigate([`/${this.#tenantsService.activeTenantId}${route}`]);
            }),
            catchError(showArchiveFailedToast),
        );
    }

    loadAll(): Observable<Dossier[]> {
        return this.#featuresService.isEnabled(DOSSIERS_ARCHIVE) ? super.loadAll() : of([]);
    }

    #removeFromActiveDossiers(archivedDossiersIds: string[]): void {
        const remainingEntities = this.#activeDossiersService.all.filter(d => !archivedDossiersIds.includes(d.dossierId));
        this.#activeDossiersService.setEntities(remainingEntities);
        this.#filesMapService.delete(archivedDossiersIds);
    }
}
