export const CUSTOMER_SUBDOMAIN_PREFIX = 'customer.'
export const BUSINESS_SUBDOMAIN_PREFIX = 'business.'

const DASHBOARD_PREFIXES = [CUSTOMER_SUBDOMAIN_PREFIX, BUSINESS_SUBDOMAIN_PREFIX] as const

export function stripDashboardSubdomain(hostname: string): string {
  const host = hostname.toLowerCase().trim()

  for (const prefix of DASHBOARD_PREFIXES) {
    if (host.startsWith(prefix)) {
      return host.slice(prefix.length)
    }
  }

  return host
}

function isDashboardSubdomainHost(hostname: string): boolean {
  const host = hostname.toLowerCase().trim()
  return DASHBOARD_PREFIXES.some((prefix) => host.startsWith(prefix))
}

export function isBusinessDashboardHost(hostname: string): boolean {
  return hostname.toLowerCase().trim().startsWith(BUSINESS_SUBDOMAIN_PREFIX)
}

export function isCustomerDashboardHost(hostname: string): boolean {
  return hostname.toLowerCase().trim().startsWith(CUSTOMER_SUBDOMAIN_PREFIX)
}

/** Resolve tenant base domain (e.g. sanihome.ir) from the current host. */
export function getBaseDomainFromHost(
  hostname: string,
  envBaseDomain?: string,
): string {
  const host = hostname.toLowerCase().trim()

  // On business.* / customer.* the hostname always wins — one build serves all tenants.
  if (isDashboardSubdomainHost(host)) {
    return stripDashboardSubdomain(host)
  }

  // localhost fallback for dev without /etc/hosts subdomains
  if (envBaseDomain?.trim()) {
    return envBaseDomain.trim()
  }

  return stripDashboardSubdomain(host)
}

export function getCustomerDashboardHost(baseDomain: string): string {
  return `${CUSTOMER_SUBDOMAIN_PREFIX}${baseDomain}`
}

export function getBusinessDashboardHost(baseDomain: string): string {
  return `${BUSINESS_SUBDOMAIN_PREFIX}${baseDomain}`
}
