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

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

export const PRODUCT_DETAIL_ERROR_MESSAGE = 'No pudimos cargar los detalles del producto.';
export const PRODUCT_DETAIL_INVALID_ID_MESSAGE = 'ID de producto invalido';

export interface ProductDetailResolvedData {
  product: CatalogItemDetail | null;
  error: string | null;
}

export const productDetailResolver: ResolveFn<ProductDetailResolvedData> = (
  route: ActivatedRouteSnapshot,
) => {
  const productId = parseIntegerParam(route.paramMap.get('id'));

  if (productId === null) {
    return of({
      product: null,
      error: PRODUCT_DETAIL_INVALID_ID_MESSAGE,
    });
  }

  return inject(CatalogService)
    .getCatalogItem(productId)
    .pipe(
      map(
        (product): ProductDetailResolvedData => ({
          product,
          error: null,
        }),
      ),
      catchError(() =>
        of({
          product: null,
          error: PRODUCT_DETAIL_ERROR_MESSAGE,
        }),
      ),
    );
};

function parseIntegerParam(value: string | null): number | null {
  if (!value) {
    return null;
  }

  const parsed = Number(value);
  return Number.isInteger(parsed) ? parsed : null;
}
