import moment from 'moment';
import { getAffLink as getAffLinkApi } from '@/api/autoshopee/public';
import { deCryptApiData } from '@/lib/utils/crypt';
import { tracerAfSetting, userSetting } from '@/plugins/setting';

class AffiliateGenerator {
  constructor(platform, storageApi, max = 5) {
    this.platform = platform;
    this.link = '';
    this.count = 0;
    this.max = max;
    this.storageApi = storageApi;
  }

  async getAffiliateUrl() {
    const restoreTracking = moment().subtract(2, 'hours').unix();
    const lastestTracking = await this.storageApi.getSync();

    if (lastestTracking && lastestTracking >= restoreTracking) {
      return '';
    }

    if (this.count >= this.max) {
      await this.storageApi.set(moment().unix());
      return '';
    }

    const getAff = await getAffLinkApi(this.platform);

    if (!(getAff.success && getAff.data)) {
      return '';
    }

    this.link = deCryptApiData(getAff.data);
    this.count++;

    return this.link;
  }
}

const affiliateGenerators = {
  shopee: new AffiliateGenerator('shopee', tracerAfSetting.affTrackingShopeeTime),
  tiki: new AffiliateGenerator('tiki', tracerAfSetting.affTrackingTikiTime),
  lazada: new AffiliateGenerator('lazada', tracerAfSetting.affTrackingLazadaTime),
};

export const getAffiliateUrl = async (platform) => {
  const generator = affiliateGenerators[platform];

  if (!generator) {
    return '';
  }

  const url = await generator.getAffiliateUrl();

  return url;
};

export const getUserInfo = async () => {
  const [
    userData,
    token,
    username,
    password,
    id,
    extensionPlan,
  ] = await Promise.all([
    userSetting.userData.getSync(),
    userSetting.userToken.getSync(),
    userSetting.userName.getSync(),
    userSetting.userPassword.getSync(),
    userSetting.userId.getSync(),
    userSetting.userExtensionPlan.getSync(),
  ]);

  /** @type {UserExtensionPlan} */
  const plan = extensionPlan;

  /** @type {UserDataPlan} */
  const userPlan = userData?.plan;

  const isAuthed = !!(token && id && userData && userData.username);
  const isPaidPlan = !!(isAuthed && plan !== 'Free');
  const isVipPlus = !!(isAuthed && plan === 'VipPlus');

  return {
    isAuthed,
    isPaidPlan,
    extensionPlan: plan,
    userPlan,
    isVipPlus,
    token,
    id,
    username,
    password,
    userData,
  };
};
