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()
}

/**
 * Fallback public invoice URL if the API response is missing `publicUrl`.
 * Prefer `invoice.publicUrl` returned by the API — this only covers edge cases.
 * Business invoices use the tenant domain (e.g. sanihome.ir), not meshkee.com.
 * Local/dev: public viewer lives on super-admin (`https://meshkee.app:5174`).
 */
export function getInvoicePublicUrlFallback(
  publicId: string,
  businessDomain = getBusinessDomain(),
): string {
  const baseOverride = import.meta.env.VITE_INVOICE_PUBLIC_BASE_URL?.trim()
  if (baseOverride) {
    return `${baseOverride.replace(/\/$/, '')}/invoices/${publicId}`
  }
  if (import.meta.env.DEV) {
    const protocol = window.location.protocol === 'http:' ? 'http:' : 'https:'
    const host =
      import.meta.env.VITE_INVOICE_PUBLIC_DEV_HOST?.trim() || 'meshkee.app'
    const port = import.meta.env.VITE_INVOICE_PUBLIC_DEV_PORT?.trim() || '5174'
    return `${protocol}//${host}:${port}/invoices/${publicId}`
  }
  const domain =
    import.meta.env.VITE_INVOICE_PUBLIC_DOMAIN?.trim() ||
    businessDomain.trim() ||
    'meshkee.com'
  return `https://${domain}/invoices/${publicId}`
}
