import { Article } from "@/contexts/catalog/domain";
import { ICatalogContext } from "@/contexts/catalog/infrastructure";
import { ICollection, IListArticles_Response_DTO, IListResponse_DTO } from "@shared/contexts";

export interface IListArticlesPresenter {
  map: (article: Article, context: ICatalogContext) => IListArticles_Response_DTO;

  mapArray: (
    articles: ICollection<Article>,
    context: ICatalogContext,
    params: {
      page: number;
      limit: number;
    }
  ) => IListResponse_DTO<IListArticles_Response_DTO>;
}

export const listArticlesPresenter: IListArticlesPresenter = {
  map: (article: Article, context: ICatalogContext): IListArticles_Response_DTO => {
    const result: IListArticles_Response_DTO = {
      id: article.id.toString(),
      catalog_name: article.catalog_name.toString(),
      id_article: article.id_article.toString(),
      reference: article.reference.toString(),
      description: article.description.toString(),
      points: article.points.toNumber(),
      retail_price: article.retail_price.toObject(),
    };
    return result;
  },

  mapArray: (
    articles: ICollection<Article>,
    context: ICatalogContext,
    params: {
      page: number;
      limit: number;
    }
  ): IListResponse_DTO<IListArticles_Response_DTO> => {
    const { page, limit } = params;

    const totalCount = articles.totalCount ?? 0;
    const items = articles.items.map((article: Article) =>
      listArticlesPresenter.map(article, context)
    );

    const result = {
      page,
      per_page: limit,
      total_pages: Math.ceil(totalCount / limit),
      total_items: totalCount,
      items,
    };

    return result;
  },
};
