import {
  BUSINESS_SUBDOMAIN_PREFIX,
  getBaseDomainFromHost,
  getBusinessDashboardHost,
  isBusinessDashboardHost,
} from '@meshkee/dashboard-core'

export const API_BASE_URL =
  import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000/api/v1'

export { BUSINESS_SUBDOMAIN_PREFIX }

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

/** Expected business admin dashboard host (e.g. business.sanihome.ir). */
export function getBusinessDashboardHostForApp(baseDomain?: string): string {
  return getBusinessDashboardHost(baseDomain ?? getBaseBusinessDomain())
}

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

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

  return isBusinessDashboardHost(host)
}

/** Domain sent to tenant resolution APIs. */
export function getBusinessDomain(): string {
  return getBaseBusinessDomain()
}
