import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, map, of } from 'rxjs';

import { CatalogFeaturedGroup } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';

export const STORE_HOME_PRODUCTS_ERROR_MESSAGE = 'No pudimos cargar los productos en este momento.';

export interface StoreHomeCatalogResolvedData {
  response: CatalogFeaturedGroup[] | null;
  error: string | null;
}

export const storeHomeCatalogResolver: ResolveFn<StoreHomeCatalogResolvedData> = () => {
  return inject(CatalogService)
    .getCatalog()
    .pipe(
      map(
        (response): StoreHomeCatalogResolvedData => ({
          response,
          error: null,
        }),
      ),
      catchError(() =>
        of({
          response: null,
          error: STORE_HOME_PRODUCTS_ERROR_MESSAGE,
        }),
      ),
    );
};
