import type { AuthUser } from '../types/auth'
import { getBusinessDomain } from './config'

const ACTIVE_BUSINESS_ID_KEY = 'meshkee_active_business_id'
const ACTIVE_BUSINESS_DOMAIN_KEY = 'meshkee_active_business_domain'

export function setActiveBusiness(user: AuthUser) {
  const domain = getBusinessDomain()
  localStorage.setItem(ACTIVE_BUSINESS_DOMAIN_KEY, domain)

  if (user.businesses.length > 0) {
    localStorage.setItem(ACTIVE_BUSINESS_ID_KEY, String(user.businesses[0].id))
  }
}

export function setActiveBusinessById(businessId: string, domain?: string) {
  localStorage.setItem(ACTIVE_BUSINESS_ID_KEY, businessId)
  localStorage.setItem(ACTIVE_BUSINESS_DOMAIN_KEY, domain ?? getBusinessDomain())
}

export function getActiveBusinessId(): string | null {
  return localStorage.getItem(ACTIVE_BUSINESS_ID_KEY)
}

export function getActiveBusinessDomain(): string {
  return localStorage.getItem(ACTIVE_BUSINESS_DOMAIN_KEY) ?? getBusinessDomain()
}

export function clearActiveBusiness() {
  localStorage.removeItem(ACTIVE_BUSINESS_ID_KEY)
  localStorage.removeItem(ACTIVE_BUSINESS_DOMAIN_KEY)
}

export const BUSINESS_PROFILE_UPDATED_EVENT = 'meshkee:business-profile-updated'

export function dispatchBusinessProfileUpdated() {
  window.dispatchEvent(new Event(BUSINESS_PROFILE_UPDATED_EVENT))
}
