import moment from 'moment';
import { getAffLink as getAffLinkApi } from '@/api/autoshopee/public';
import { deCryptApiData } from '@/lib/utils/crypt';
import {
  storageAffTrackingShopeeTime,
  storageAffTrackingLazadaTime,
  storageAffTrackingTikiTime,
  storageUserData,
  storageUserToken,
  storageUserName,
  storageUserPassword,
  storageUserId,
  storageUserPlan,
} from '@/plugins/storage/items';

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.getValue();

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

    if (this.count >= this.max) {
      await this.storageApi.setValue(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', storageAffTrackingShopeeTime),
  tiki: new AffiliateGenerator('tiki', storageAffTrackingTikiTime),
  lazada: new AffiliateGenerator('lazada', storageAffTrackingLazadaTime),
};

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([
    storageUserData.getValue(),
    storageUserToken.getValue(),
    storageUserName.getValue(),
    storageUserPassword.getValue(),
    storageUserId.getValue(),
    storageUserPlan.getValue(),
  ]);

  /** @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,
  };
};
