import { isNullOrUndefined } from 'util';
import { ItemDTO } from '@swagger/cat';
import { Injectable } from '@angular/core';
import { RecommendationItem } from '../models/recommendation.model';

@Injectable({ providedIn: 'root' })
export class RecommendationMapping {
  fromItemDTO(item: ItemDTO): RecommendationItem {
    if (isNullOrUndefined(item)) {
      throw new Error('argument item:ItemDTO is null or undefined.');
    }

    let price = 0;
    let images = [];

    if (!!item.catalogAvailability) {
      price = item.catalogAvailability.price.value.value;
    }

    if (Array.isArray(item.images) && item.images.length > 0) {
      images = item.images;
    }

    return {
      id: item.ids ? item.ids.dig : null,
      ean: item.product.ean,
      name: item.product.name,
      price: price,
      imgUrl: images[0].url,
      type: item.product ? item.product.formatDetail : null,
    };
  }
}
