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

import { ApiPaginatedResponse } from '../../../../core/services/api-paginated-response.interface';
import { Product } 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 StoreHomeProductsResolvedData {
  response: ApiPaginatedResponse<Product[]> | null;
  error: string | null;
}

export const storeHomeProductsResolver: ResolveFn<StoreHomeProductsResolvedData> = () => {
  return inject(CatalogService)
    .getProductos({ page: 1 })
    .pipe(
      map(
        (response): StoreHomeProductsResolvedData => ({
          response,
          error: null,
        }),
      ),
      catchError(() =>
        of({
          response: null,
          error: STORE_HOME_PRODUCTS_ERROR_MESSAGE,
        }),
      ),
    );
};
