const psl = require('psl');

const normalizeHost = (value) => {
  if (typeof value !== 'string') {
    return '';
  }

  return value
    .trim()
    .toLowerCase()
    .replace(/^https?:\/\//, '')
    .replace(/^www\./, '')
    .split('/')[0]
    .split('?')[0]
    .split('#')[0]
    .split(':')[0];
};

const getRegistrableDomain = (value) => {
  const host = normalizeHost(value);

  if (!host) {
    return '';
  }

  return psl.get(host) ?? host;
};

export const main = async (params) => {
  const domain = getRegistrableDomain(params?.domain);
  const companies = Array.isArray(params?.companies) ? params.companies : [];

  const matchingCompany = companies.find((company) => {
    const companyDomain = getRegistrableDomain(
      company?.domainName?.primaryLinkUrl,
    );

    return companyDomain !== '' && companyDomain === domain;
  });

  const companyId =
    typeof matchingCompany?.id === 'string' ? matchingCompany.id : '';

  return {
    companyId,
    hasMatch: companyId !== '',
  };
};