import queryString from 'query-string';
import configShopee from '@/config/shopee';

export const shopeeUrlMatchProductId = (url) => {
  const urlRegSlug = url.match(configShopee.regexPattern.productShopeeSlug);

  if (urlRegSlug) {
    return {
      shopId: urlRegSlug[1],
      itemId: urlRegSlug[2],
      productId: urlRegSlug[2],
    };
  }

  const urlRegId = url.match(configShopee.regexPattern.productShopeeId);

  if (urlRegId) {
    return {
      shopId: urlRegId[1],
      itemId: urlRegId[2],
      productId: urlRegId[2],
    };
  }

  return null;
};

export const shopeeUrlMatchOrderId = (url) => {
  const match = url.match(/sale\/order\/(\d*)$/);

  if (!(match && match[1])) {
    return null;
  }

  return {
    orderId: match[1],
  };
};

export const shopeeUrlMatchSellerPrint = (url) => {
  if (!url.includes('banhang.shopee.vn/awbprint')) {
    return null;
  }

  const urlQuery = queryString.parseUrl(url).query;

  if (!urlQuery.job_id) {
    return null;
  }

  return {
    jobUrl: url,
    from: 'shopee',
    jobId: urlQuery.job_id,
    shopId: urlQuery.shop_id,
  };
};

export const lazadaUrlMatchSellerPrint = (url) => {
  if (!url.includes('sellercenter.lazada.vn/apps/order/print')) {
    return null;
  }

  const urlQuery = queryString.parseUrl(url).query;

  if (!urlQuery.jobId) {
    return null;
  }

  return {
    jobUrl: url,
    from: 'lazada',
    jobId: urlQuery.jobId,
  };
};

export const tiktokUrlMatchSellerPrint = (url) => {
  if (!url.includes('seller-vn.tiktok.com/easesafe/oec_fulfillment_doc_tts/object')) {
    return null;
  }

  const match = url.match(/object\/(wsos\w+)/);

  if (!(match && match[1])) {
    return null;
  }

  return {
    jobUrl: url,
    jobId: match[1],
    from: 'tiktok',
  };
};

const SHOPEE_RESERVED_SEGMENTS = [
  'search', 'buyer', 'cart', 'account', 'chat', 'order',
  'product', 'mall', 'voucher', 'blog', 'help',
];

export const shopeeUrlMatchShopUsername = (url) => {
  const match = url.match(/^https:\/\/shopee\.vn\/([^/?#]+)\/?(\?.*)?$/);

  if (!match) {
    return null;
  }

  const segment = match[1];

  if (SHOPEE_RESERVED_SEGMENTS.includes(segment)) {
    return null;
  }

  return { username: segment };
};

export const shopeeUrlMatchSearch = (url) => {
  if (!url.includes('shopee.vn/search')) {
    return null;
  }

  const parsed = queryString.parseUrl(url);

  if (!parsed.query.keyword) {
    return null;
  }

  return {
    keyword: parsed.query.keyword,
  };
};

export const tiktokUrlMatchProductId = (url) => {
  const match = url.match(/tiktok\.com\/pdp\/(\d*)/);

  if (!(match && match[1])) {
    return null;
  }

  return {
    productId: match[1],
  };
};
