import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of } from 'rxjs';
import { environment } from '../../../environments/environment';

export interface BackendHealth {
  status: 'ok';
  uptimeSeconds: number;
  service: string;
  version: string;
}

export type HomeStatus =
  | { state: 'loading' }
  | { state: 'ok'; health: BackendHealth }
  | { state: 'error' };

/**
 * Fetches the BFF's `/api/health` once on instantiation and exposes
 * the result as a Signal. Doubles as a smoke test of the SPA→BFF
 * stack (CORS, OTel trace propagation, Pino log correlation —
 * everything we wired in the observability foundation PRs).
 *
 * The BFF base URL comes from `environment.ts` (per ADR-0018); the
 * per-environment build target swaps the file via `fileReplacements`.
 */
@Injectable({ providedIn: 'root' })
export class HomeStatusService {
  private static readonly HEALTH_URL = `${environment.bffApiBaseUrl}/health`;
  private readonly http = inject(HttpClient);

  readonly status = toSignal(
    this.http.get<BackendHealth>(HomeStatusService.HEALTH_URL).pipe(
      map((health): HomeStatus => ({ state: 'ok', health })),
      catchError(() => of<HomeStatus>({ state: 'error' })),
    ),
    // The cast to `HomeStatus` (rather than `as const`) lets toSignal's
    // overload pick `Signal<T>` instead of `Signal<T | U>` and keeps
    // the consuming `.state` narrowing clean for the component.
    { initialValue: { state: 'loading' } as HomeStatus },
  );
}
