import { getListFlashSale, getTimeSlotFlashSale } from '@/api/shopee/seller/flashsale';
import { KVCheckLock } from '@/plugins/kv';

export const unixTime = (num) => new Date(num * 1000);

export const getFlashSaleDataTimeId = async (timeId) => {
  const listFlashSale = await getListFlashSale(0, 'next', 100);

  return listFlashSale.find((item) => item.timeslot_id === timeId);
};

export const getListSlotTimeAll = async () => {
  const listSlot = (await getTimeSlotFlashSale()).map((item) => ({
    timeSlotId: item.timeslot_id,
    timeStart: unixTime(item.start_time),
    timeEnd: unixTime(item.end_time),
  }));

  return listSlot;
};

/**
 * @param {string} type
 * @param {string} id
 * @param {number} ttl
 */
export const getKvLockApi = async (type, id, ttl = 30) => {
  const keyLock = ['shopee-flashsale-scheduler', type, id].join('-');
  const KvLocker = new KVCheckLock(keyLock);

  const isLocked = !!(await KvLocker.getKv());

  if (isLocked) {
    return {
      KvLocker: null,
    };
  }

  await KvLocker.setKv({
    date: new Date(),
    now: Date.now(),
  }, ttl);

  return {
    KvLocker,
  };
};
