const buildUrl = (landingPage) => {
  try {
    return new URL(landingPage);
  } catch (error) {
    return null;
  }
};

export const buildOseCardPreviewUrl = (landingPage, cardCode) => {
  const url = buildUrl(landingPage);

  if (!url) {
    return "";
  }

  if (cardCode) {
    url.searchParams.set("ose-card", cardCode);
  }

  return url.toString();
};

export const buildOseCardCouponUrl = (
  landingPage,
  cardCode,
  couponType,
  couponCode,
  affiliateCode
) => {
  const url = buildUrl(landingPage);

  if (!url) {
    return "";
  }

  switch (couponType) {
    case "優惠代碼":
      if (couponCode) {
        url.searchParams.set("oc", couponCode);
      }
      break;
    case "推薦代碼":
      if (affiliateCode) {
        url.searchParams.set("ac", affiliateCode);
      }
      break;
    case "優惠代碼+推薦代碼":
      if (couponCode) {
        url.searchParams.set("oc", couponCode);
      }
      if (affiliateCode) {
        url.searchParams.set("ac", affiliateCode);
      }
      break;
    case "行銷圖卡+優惠代碼":
      if (cardCode) {
        url.searchParams.set("mc", cardCode);
      }
      if (couponCode) {
        url.searchParams.set("oc", couponCode);
      }
      break;
    case "行銷圖卡+推薦代碼":
      if (cardCode) {
        url.searchParams.set("mc", cardCode);
      }
      if (affiliateCode) {
        url.searchParams.set("ac", affiliateCode);
      }
      break;
    case "行銷圖卡+優惠代碼+推薦代碼":
      if (cardCode) {
        url.searchParams.set("mc", cardCode);
      }
      if (couponCode) {
        url.searchParams.set("oc", couponCode);
      }
      if (affiliateCode) {
        url.searchParams.set("ac", affiliateCode);
      }
      break;
    default:
      return "";
  }

  return url.toString();
};
