import { Injectable, inject, signal } from '@angular/core'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, switchMap } from 'rxjs'; import { PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' }; @Injectable() export class PacienteRiesgoState { private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); // `undefined` until the input is set; `null` is a patient without `pac_id`. readonly pacId = signal(undefined); readonly estado = toSignal(toObservable(this.pacId).pipe( switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe( map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), catchError(() => of({ tipo: 'error' })), startWith(CARGANDO), )), ), { initialValue: CARGANDO }); }