const { sellerProductImageBuilder } = require("../helpers/image-src-builder");
const { checkPOItemStock } = require("../services/purchase-order.service");

const isSellerPOEnabled = (enabledPO, sellerId) => {
  if (typeof enabledPO === "boolean") {
    return enabledPO;
  }

  if (Array.isArray(enabledPO)) {
    return enabledPO.includes(sellerId);
  }

  if (enabledPO instanceof Set) {
    return enabledPO.has(sellerId);
  }

  if (enabledPO && typeof enabledPO === "object") {
    return !!enabledPO[sellerId];
  }

  return false;
};

const productMapper = async (sellerProducts, enabledPO = false) => {
  const __sellerProducts = Array.isArray(sellerProducts)
    ? sellerProducts
    : [sellerProducts];

  const _sellerProducts = await Promise.all(
    __sellerProducts.map(
      async ({
        id,
        seller_id,
        menu,
        description,
        price,
        discounted_price,
        photo,
        quantity_limit,
        stocks,
        available,
        sku,
        menus,
        seller_dashboard_src,
        product_variations = [],
        product_images = [],
        seller
      }) => {
        const shouldCheckProductPO = isSellerPOEnabled(enabledPO, seller_id);

        const poStocks = shouldCheckProductPO ? await checkPOItemStock(id) : 0;
        const itemAvailableStocks =
          poStocks && poStocks.availableStock ? poStocks.availableStock : 0;

        const response = {
          id,
          seller_id,
          name: menu,
          description,
          price,
          discounted_price,
          photo: [],
          quantity_limit,
          stocks,
          available,
          sku,
          category: menus,
          seller_dashboard_src,
          poStocks: itemAvailableStocks,
          seller: {
            id: seller.id,
            company_name: seller.company_name,
            shop_name: seller.shop_name,
          },
        };

        if (photo) {
          response.photo.push({
            photo: sellerProductImageBuilder(photo, seller_dashboard_src),
          });
        }

        product_images.forEach(({ id, file_name, is_thumbnail }) => {
          if (file_name) {
            response.photo.push({
              id,
              photo: sellerProductImageBuilder(file_name, true),
              is_thumbnail,
            });
          }
        });

        const productVariation = await Promise.all(
          product_variations.map(
            async ({
              id,
              variation,
              description,
              quantity_limit,
              discounted_price,
              hasSubVariation,
              isAvailable,
              variationImage,
              sku,
              stocks,
              ProductSubVariations = [],
            }) => {
              const variationPoStocks = shouldCheckProductPO
                ? await checkPOItemStock(id)
                : 0;

              const variationResponse = {
                id,
                name: variation,
                description,
                quantity_limit,
                discounted_price,
                has_sub_variation: hasSubVariation,
                is_available: isAvailable,
                photo: variationImage
                  ? sellerProductImageBuilder(variationImage, true)
                  : null,
                sku,
                stocks,
                variationPoStocks:
                  variationPoStocks && variationPoStocks.availableStock
                    ? variationPoStocks.availableStock
                    : 0,
              };

              variationResponse.product_sub_variations =
                ProductSubVariations.map(
                  ({
                    id,
                    custom,
                    description,
                    price,
                    discounted_price,
                    quantity_limit,
                    stocks,
                    sku,
                    isAvailable,
                    photo,
                  }) => ({
                    id,
                    name: custom,
                    description,
                    price,
                    discounted_price,
                    quantity_limit,
                    stocks,
                    sku,
                    is_available: isAvailable,
                    photo: photo
                      ? sellerProductImageBuilder(photo, true)
                      : null,
                  })
                );

              return variationResponse;
            }
          )
        );

        response.product_variations = productVariation;
        return response;
      }
    )
  );

  return _sellerProducts;
};

module.exports = productMapper;