import { notifications } from "../../utils/chrome";
import {
  QueryWangLinkParams,
  SearchShopParams,
  SearchSimilarShopParams,
  fetchShopWangLink,
  fetchShops,
  fetchSimilarShop,
  searchTaobaoShop,
} from "./common";

/**
 * 基于background做一个脚本扩展
 * @param clickboardData
 */
export async function searchTaobaoShopInBackground(params: SearchShopParams) {
  const shopName = params.shopName;
  if (!shopName) {
    notifications("apptip", "没有店铺名称,无法进行店铺搜索");
    throw new Error("没有店铺名称");
  }
  return fetchShops(params).catch((e) => {
    notifications("apptip", "相似店铺查询失败,请重新打开页面登录淘宝后重试");
    throw new Error(e);
  });
}

export async function searchTaobaoSimilarShopInBackground(
  params: SearchSimilarShopParams
) {
  const { similarUrl: shopUrl } = params;
  if (!shopUrl) {
    notifications("apptip", "主店铺地址不能为空");
    throw new Error("没有店铺地址");
  }
  return fetchSimilarShop(params).catch((e) => {
    notifications("apptip", "相似店铺查询失败,请重新打开页面登录淘宝后重试");
    throw new Error(e);
  });
}

export async function queryShopWangLinkInBackground(
  params: QueryWangLinkParams
) {
  const { shopName, shopUrl } = params;
  if (!shopUrl) {
    notifications("apptip", "主店铺地址不能为空");
    throw new Error("没有店铺地址");
  }
  if (!shopName) {
    notifications("apptip", "没有店铺名称,无法获取旺旺链接");
    throw new Error("没有店铺名称");
  }
  return fetchShopWangLink(params).catch((e) => {
    notifications("apptip", "获取旺旺链接失败,请重新打开页面登录淘宝后重试");
    throw new Error(e);
  });
}

/**
 * 打开搜索店铺链接
 * @param shopName
 * @returns
 */
export async function openSearchShopInBackground(shopName: string) {
  if (!shopName) {
    notifications("apptip", "没有店铺名称,无法进行店铺搜索");
    throw new Error("没有店铺名称");
  }
  return searchTaobaoShop(shopName);
}
