const { findSellerByDomain } = require("../db/seller.db")

function normalizeDomain(hostname) {
  return hostname.replace(/^www\./, "")
}

async function findSellerFromLink(url) {
  let hostname

  try {
    hostname = new URL(url).hostname
  } catch {
    return null
  }

  const domain = normalizeDomain(hostname)

  const seller = await findSellerByDomain(domain)
  if (seller) {
    return seller
  }

  const domainParts = domain.split(".")
  for (let i = 1; i <= domainParts.length - 2; i += 1) {
    const parentDomain = domainParts.slice(i).join(".")
    const parentSeller = await findSellerByDomain(parentDomain)
    if (parentSeller) {
      return parentSeller
    }
  }

  return null
}

module.exports = {
  findSellerFromLink,
}
