import '@/types/Shopee/Seller/SubAccount';

import { apiShopeeSeller } from '@/api/shopee/seller/init';

/**
 *
 * @param {object} params
 * @param {number} params.accountId
 * @param {string} [params.spcCds]
 * @returns {Promise<ShopeeSubAccount|null>}
 */
export const getShopeeSubAccountInfo = async (params = {}) => {
  const query = {};

  if (params.accountId) {
    query.account_id = params.accountId;
  }

  if (params.spcCds) {
    query.SPC_CDS = params.spcCds;
  }

  try {
    const result = await apiShopeeSeller.get('/api/selleraccount/subaccount/get/', {
      params: query,
    });

    if (result && !result.code) {
      return result;
    }

    return null;
  } catch (error) {
    return null;
  }
};

/**
 *
 * @param {object} params
 * @param {number} params.accountId
 * @param {string} [params.spcCds]
 * @returns {Promise<ShopeeSubAccount|null>}
 */
export const getShopeeSubAccountFramework = async (params = {}) => {
  const query = {};

  if (params.accountId) {
    query.account_id = params.accountId;
  }

  if (params.spcCds) {
    query.SPC_CDS = params.spcCds;
  }

  try {
    const result = await apiShopeeSeller.get('/api/framework/selleraccount/subaccount/get/', {
      params: query,
    });

    if (result && !result.code) {
      return result;
    }

    return null;
  } catch (error) {
    return null;
  }
};

/**
 *
 * @param {object} params
 * @param {number} params.accountId
 * @param {string} [params.spcCds]
 * @param {string} [params.country]
 * @param {number} [params.pageIndex]
 * @param {number} [params.pageSize]
 * @param {number} [params.searchType]
 * @param {string} [params.searchContent]
 * @returns {Promise<ShopeeSubAccountShop[]>}
 */
export const getShopeeSubAccountShopList = async (params = {}) => {
  const {
    spcCds,
    pageIndex = 1,
    pageSize = 16,
    searchType = 1,
  } = params;

  const query = {
    page_index: pageIndex,
    page_size: pageSize,
    search_type: searchType,
  };

  if (params.accountId) {
    query.account_id = params.accountId;
  }

  if (spcCds) {
    query.SPC_CDS = spcCds;
  }

  try {
    const result = await apiShopeeSeller.get('/api/selleraccount/subaccount/get_shop_list/', {
      params: query,
    });

    if (result && !result.code) {
      return result.shops || [];
    }

    return [];
  } catch (error) {
    return [];
  }
};

export const getShopeeIsSubAccount = async () => {
  const subAccountInfo = await getShopeeSubAccountInfo();

  return {
    isSubAccount: subAccountInfo && subAccountInfo.sub_account_id,
    shopId: subAccountInfo && subAccountInfo.sub_account_id ? subAccountInfo.sub_account_id : 0,
  };
};
