export function hasWwwDomainPrefix(value: string) {
  const hostname = value
    .trim()
    .toLowerCase()
    .replace(/^https?:\/\//, "");

  return hostname.startsWith("www.");
}

export function getWwwDomainSuggestion(value: string) {
  const hostname = value
    .trim()
    .toLowerCase()
    .replace(/^https?:\/\//, "")
    .replace(/[/?#].*$/, "")
    .replace(/:\d+$/, "");
  const domain = hostname
    .replace(/^www\./, "")
    .replace(/[^a-z0-9.-]/g, "")
    .replace(/^\.+|\.+$/g, "");

  return domain || "officialsite.kr";
}

export function getWwwDomainInputMessage(value: string) {
  return `www를 제외한 도메인으로 입력해주세요. 예: ${getWwwDomainSuggestion(value)}`;
}

const DOMAIN_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DOMAIN_TLD_PATTERN = /^(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})$/;

export function isValidDomainInput(value: string) {
  const domain = value
    .trim()
    .toLowerCase()
    .replace(/^https?:\/\//, "")
    .replace(/\/$/, "");

  if (
    !domain ||
    domain.length > 253 ||
    domain.includes(":") ||
    domain.includes("/") ||
    domain.includes("?") ||
    domain.includes("#")
  ) {
    return false;
  }

  const labels = domain.split(".");

  if (labels.length < 2 || !DOMAIN_TLD_PATTERN.test(labels.at(-1) ?? "")) {
    return false;
  }

  return labels.every((label) => DOMAIN_LABEL_PATTERN.test(label));
}

export function getInvalidDomainInputMessage() {
  return "구매하신 도메인 주소 형식으로 입력해주세요. 예: officialsite.kr";
}
