import '@/types/Shopee/Seller/Flashsale';
import delay from 'delay';
import moment from 'moment';
import { apiShopeeSeller } from '@/api/shopee/seller/init';

const RETRY_SET_LIST_PRODUCT = {
  maxRetry: 3,
  delay: 1000,
};

/**
 *
 * @returns {Promise<ShopeeFsTime[]>}
 */
export const getTimeSlotFlashSale = async () => {
  const result = await apiShopeeSeller.get('/api/marketing/v4/shop_flash_sale/time_slot/', {
    params: {
      start_time: moment().unix(),
      end_time: moment().add(1, 'month').unix(),
    },
  });

  return result.data || [];
};

/**
 *
 * @param {number} timeId
 * @returns {Promise<ShopeeFsCreateResult>}
 */
export const createFlashSaleIdFromTime = async (timeId) => {
  const payload = {
    time_slot_id: Number(timeId),
  };

  const result = await apiShopeeSeller.post('/api/marketing/v4/shop_flash_sale/set/', payload);

  return result.data || null;
};

/**
 *
 * @param {number} flashSaleId
 * @param {number} timeId
 * @returns {Promise<ShopeeFsCreateResult>}
 */
export const removeFlashSaleId = async (flashSaleId, timeId) => {
  const payload = {
    flash_sale_id: Number(flashSaleId),
    time_slot_id: Number(timeId),
    status: 0,
  };

  const result = await apiShopeeSeller.post('/api/marketing/v4/shop_flash_sale/set/', payload);

  return result.data || null;
};

/**
 *
 * @param {number} flashSaleId
 * @param {ShopeeFsSetListItem[]} listItem
 * @returns {Promise<ShopeeFsSetResult>}
 */
export const updateFlashSaleSetListProduct = async (flashSaleId = 0, listItem = []) => {
  const payloadSet = {
    flash_sale_id: Number(flashSaleId),
    items: listItem,
    use_global_category: true,
  };

  /** @type {ShopeeFsSetResult} */
  let resultSet = null;

  for (let countRetry = 0; countRetry < RETRY_SET_LIST_PRODUCT.maxRetry; countRetry++) {
    resultSet = (await apiShopeeSeller.post('/api/marketing/v4/shop_flash_sale/batch_items/set/', payloadSet)).data || null;

    const isRetrySet = resultSet && resultSet.failed_items && resultSet.failed_items.length;

    if (!isRetrySet) {
      break;
    }

    await delay(RETRY_SET_LIST_PRODUCT.delay);
  }

  return resultSet;
};

/**
 *
 * @param {number} flashSaleId
 * @param {ShopeeFsIndexListItem[]} listIndex
 */
export const updateFlashSaleIndexListProduct = async (flashSaleId = 0, listIndex = []) => {
  const payloadIndex = {
    flash_sale_id: Number(flashSaleId),
    display_sequence_list: listIndex,
  };

  const result = await apiShopeeSeller.post('/api/marketing/v4/shop_flash_sale/item_seq/', payloadIndex);

  return result.data || null;
};

/**
 *
 * @param {number} offset
 * @param {ShopeeFsStatus} status
 * @param {number} limit
 * @returns {Promise<ShopeeFSCampagin[]>}
 */
export const getListFlashSale = async (offset = 0, status = 'all', limit = 10) => {
  const statusType = {
    all: 0,
    next: 1,
    current: 2,
    end: 3,
  };

  const result = await apiShopeeSeller.get('/api/marketing/v4/shop_flash_sale/list/', {
    params: {
      offset,
      limit,
      type: statusType[status],
    },
  });

  return result.data.flash_sale_list || [];
};

/**
 *
 * @param {number} flashSaleId
 * @returns {Promise<ShopeeFsItemFromId>}
 */
export const getFlashSaleId = async (flashSaleId) => {
  const result = await apiShopeeSeller.get('/api/marketing/v4/shop_flash_sale/batch_items/get', {
    params: {
      flash_sale_id: Number(flashSaleId),
      offset: 0,
      limit: 100,
    },
  });

  if (result.data && result.data.model_info_str) {
    result.data.model_info = JSON.parse(result.data.model_info_str);
    delete result.data.model_info_str;
  }

  return result.data;
};

/**
 *
 * @param {number} flashSaleId
 * @returns {Promise<ShopeeFSCampagin>}
 */
export const getFlashSaleCampaignId = async (flashSaleId) => {
  const result = await apiShopeeSeller.get('/api/marketing/v4/shop_flash_sale/get/', {
    params: {
      flash_sale_id: Number(flashSaleId),
    },
  });

  return result.data;
};

/**
 *
 * @param {number} limit
 * @param {number} page
 * @returns {Promise<ShopeeFSReport[]>}
 */
export const getFlashSaleReport = async (limit = 20, page = 1) => {
  const { result } = await apiShopeeSeller.get('/api/mydata/v2/marketing/flash-sale/overview/', {
    params: {
      page_size: limit,
      page_offset: page,
      sort_by: 'end_day.desc',
      order_type: 'confirmed',
    },
  });

  return result.items || [];
};

/**
 * @param {number} page
 * @param {number} limit
 * @param {string} cursor
 * @param {string} search
 * @param {("name"|"id")} by
 */
export const getProductListFlashSale = async (page = 1, limit = 100, cursor = '', search = '', by = 'name') => {
  const payload = {
    limit,
    page,
    is_ads: 0,
    need_brand: 0,
    need_item_model: 0,
  };

  if (cursor) {
    payload.cursor = cursor;
  }

  if (search) {
    const searchBy = {
      id: 1,
      name: 0,
    };
    payload.search_content = search;
    payload.search_type = searchBy[by];
  }

  /** @type {ShopeeFSProductSearch} */
  const data = (
    await apiShopeeSeller.get('/api/marketing/v4/public/product_selector/', {
      params: payload,
    })
  ).data;

  return {
    listItem: data,
    cursor: data.cursor,
    total: data.total_count,
    count: data.item_list.length,
  };
};
