import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, shareReplay } from 'rxjs';
import { ENUMS_API_ROUTES } from './constants/apiRoutes';
import { TEnumApi } from './models';
import { IApiEnumResponse } from './models/io';

@Injectable({ providedIn: 'root' })
export class EnumsService {
  constructor(private http: HttpClient) {}

  private apiRoutes = ENUMS_API_ROUTES;
  private readonly cache = new Map<TEnumApi, Observable<IApiEnumResponse[]>>();

  getAll(type: TEnumApi): Observable<IApiEnumResponse[]> {
    const cached = this.cache.get(type);
    if (cached) {
      return cached;
    }

    const request$ = this.http
      .get<IApiEnumResponse[]>(this.apiRoutes[type])
      .pipe(shareReplay({ bufferSize: 1, refCount: true }));

    this.cache.set(type, request$);
    return request$;
  }
}
