import { ModelApiLoader } from '@/api/model';
import unixTimestamp from 'unix-timestamp';
import { getDateOnly } from '@/lib/utils/moment';

export const ShopeeSpyList = new ModelApiLoader('shopee_spy_list');
export const ShopeeSpyLog = new ModelApiLoader('shopee_spy_log');

ShopeeSpyList.createIndex({
  index: {
    fields: ['type', 'shopId', 'productId'],
  },
});

ShopeeSpyLog.createIndex({
  index: {
    fields: ['id', 'date', 'type'],
  },
});

const getPayloadSpy = (payload) => {
  if (payload.shop_id && payload.item_id) {
    /** @type {ShopeeProductData} */
    const product = payload;

    return {
      type: 'product',
      productId: payload.item_id,
      shopId: payload.shop_id,
      shopName: product.shop_data.account.username,
      shopMall: product.shop_data.is_official_shop,
      name: product.name,
      time: unixTimestamp.toDate(product.ctime),
      location: product.shop_data.shop_location,
      image: product.image,
      price: product.price,
      promotion: product.price,
      discount: 0,
      stock: 0,
      countRating: product.total_rating_count,
      countLike: product.liked_count,
      countView: product.view_count,
      sold: product.global_sold,
      sale: product.global_sold * product.price,
      variation: product.models.length,
      soldStart: product.global_sold,
      soldInc: 0,
      url: '',
    };
  }

  /** @type {ShopeeShopData} */
  const shop = payload;

  return {
    type: 'shop',
    name: shop.name,
  };
};

export const getRefId = (payload) => {
  if (payload.shop_id && payload.item_id) {
    return ['product', payload.shop_id, payload.item_id].join('-');
  }

  return ['shop', payload.shop_id].join('-');
};

export const createSpy = (payload) => {
  return ShopeeSpyList.insert(getPayloadSpy(payload), getRefId(payload));
};

export const fetchSpyUpdate = async (payload, newData) => {
  if (payload.type === 'product') {
    /** @type {ShopeeProductData} */
    const product = newData;

    const update = {
      sold: product.global_sold,
      sale: product.global_sold * product.price,
      soldInc: product.global_sold - payload.soldStart,
    };

    const dateCurrent = getDateOnly(new Date());

    const queryLog = {
      date: dateCurrent,
      id: payload._id,
      type: 'product-sold',
    };

    const isLog = await ShopeeSpyLog.findMany(queryLog);

    if (!isLog.length) {
      await ShopeeSpyLog.insert({
        ...queryLog,
        ...update,
      });
    }

    return ShopeeSpyList.updateId(payload._id, update);
  }

  return null;
};
