import { Injectable, inject } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';
import { ProductCardConfig, CategoryCardConfig } from '../../shared/models/ui';
import { BACKOFFICE_DATA_PROVIDER } from './backoffice-data-provider.token';

/**
 * Single access point for backoffice catalog data. Requests are cached with
 * shareReplay so the many gateways that read products/categories (products,
 * categories, moderation, dashboard metrics) share one in-flight request per
 * endpoint instead of each firing their own. A failed request clears the cache
 * so the next call retries instead of replaying the error forever.
 */
@Injectable({ providedIn: 'root' })
export class BackofficeDataService {
  private readonly provider = inject(BACKOFFICE_DATA_PROVIDER);

  private products$: Observable<ProductCardConfig[]> | null = null;
  private categories$: Observable<CategoryCardConfig[]> | null = null;

  loadProducts(): Observable<ProductCardConfig[]> {
    if (!this.products$) {
      this.products$ = this.provider.loadProducts().pipe(
        catchError(error => {
          this.products$ = null;
          return throwError(() => error);
        }),
        shareReplay({ bufferSize: 1, refCount: false }),
      );
    }
    return this.products$;
  }

  loadCategories(): Observable<CategoryCardConfig[]> {
    if (!this.categories$) {
      this.categories$ = this.provider.loadCategories().pipe(
        catchError(error => {
          this.categories$ = null;
          return throwError(() => error);
        }),
        shareReplay({ bufferSize: 1, refCount: false }),
      );
    }
    return this.categories$;
  }
}
