import {
  CUSTOMER_SUBDOMAIN_PREFIX,
  getBaseDomainFromHost,
  getBusinessDashboardHost,
  getCustomerDashboardHost,
  isCustomerDashboardHost,
} from '@meshkee/dashboard-core'

export { CUSTOMER_SUBDOMAIN_PREFIX }

/** Base tenant domain without customer. prefix (e.g. sanihome.ir). */
export function getBaseBusinessDomain(hostname = window.location.hostname): string {
  return getBaseDomainFromHost(hostname, import.meta.env.VITE_BUSINESS_DOMAIN)
}

/** Expected customer dashboard host (e.g. customer.sanihome.ir). */
export function getCustomerDashboardHostForApp(baseDomain?: string): string {
  return getCustomerDashboardHost(baseDomain ?? getBaseBusinessDomain())
}

export function isAllowedCustomerHost(hostname = window.location.hostname): boolean {
  const host = hostname.toLowerCase().trim()

  if (host === 'localhost' || host === '127.0.0.1') {
    return true
  }

  return isCustomerDashboardHost(host)
}

/** Domain sent to tenant resolution and customer registration APIs. */
export function getTenantDomain(): string {
  return getBaseBusinessDomain()
}

/** Open the matching business dashboard (local: port 5173). */
export function getBusinessDashboardUrl(): string {
  const host = getBusinessDashboardHost(getBaseBusinessDomain())
  const { protocol, port } = window.location
  const businessPort = port === '5175' ? '5173' : port
  const portSuffix = businessPort ? `:${businessPort}` : ''
  return `${protocol}//${host}${portSuffix}/`
}
