import { inject } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { of, EMPTY, Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

import { IDocument } from '../document.model';
import { DocumentService } from '../service/document.service';

const documentResolve = (route: ActivatedRouteSnapshot): Observable<null | IDocument> => {
  const router = inject(Router);
  const translate = inject(TranslateService);
  const documentService = inject(DocumentService);
  const id = route.params['id'];
  if (id) {
    return inject(DocumentService)
      .find(id)
      .pipe(
        mergeMap((documentResponse: HttpResponse<IDocument>) => {
          if (documentResponse.body) {
            const document = documentResponse.body;
            
            // Check if is /edit route, and the state of the Document
            const path = route.routeConfig?.path;
            if (path && path.endsWith('/edit') && !documentService.canUpdate(document)) {
              router.navigate(['/document', id, 'view'], {
                state: { message: translate.instant('resilientApp.document.home.editNotAllowedForState') }
              });
              return EMPTY;
            } else {
              return of(document);
            }
          } else {
            router.navigate(['404']);
            return EMPTY;
          }
        }),
      );
  }
  return of(null);
};

export default documentResolve;
