import { Injectable, computed, inject, signal } from '@angular/core'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, switchMap } from 'rxjs'; import { DominioRiesgo, 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 dominio = signal('cacu'); // The patient and her domain are one query, so changing both never asks for the patient in the wrong domain. private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() })); readonly estado = toSignal(toObservable(this.consulta).pipe( switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe( map((respuesta): PacienteRiesgoEstado => { const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id); return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos }; }), catchError(() => of({ tipo: 'error' })), startWith(CARGANDO), )), ), { initialValue: CARGANDO }); }