/** Optional business-dashboard CMS modules. Always-on areas are not listed. */
export const BUSINESS_DASHBOARD_MODULE_IDS = [
  'products',
  'store',
  'portfolio',
  'blog',
  'warehouse',
  'videos',
] as const

/** Optional customer-dashboard modules. Always-on: home, profile, addresses, orders, favorites. */
export const CUSTOMER_MODULE_IDS = ['customer_products'] as const

/** All optional modules stored in `settings.modules.enabled`. */
export const BUSINESS_MODULE_IDS = [
  ...BUSINESS_DASHBOARD_MODULE_IDS,
  ...CUSTOMER_MODULE_IDS,
] as const

export type BusinessDashboardModuleId =
  (typeof BUSINESS_DASHBOARD_MODULE_IDS)[number]
export type CustomerModuleId = (typeof CUSTOMER_MODULE_IDS)[number]
export type BusinessModuleId = (typeof BUSINESS_MODULE_IDS)[number]

/** Home dashboard chart slots (super-admin selectable). */
export const HOME_CHART_IDS = [
  'none',
  'orders_30d',
  'customers_joined_1y',
  'blog_views_30d',
  'products_added_1y',
] as const

export type HomeChartId = (typeof HOME_CHART_IDS)[number]

/**
 * Existing tenants without saved modules keep every business-dashboard module
 * enabled. Customer modules stay opt-in.
 */
export const DEFAULT_ENABLED_BUSINESS_MODULES: BusinessModuleId[] = [
  ...BUSINESS_DASHBOARD_MODULE_IDS,
]

export const DEFAULT_HOME_CHARTS: [HomeChartId, HomeChartId] = [
  'orders_30d',
  'customers_joined_1y',
]

const MODULE_ID_SET = new Set<string>(BUSINESS_MODULE_IDS)
const HOME_CHART_ID_SET = new Set<string>(HOME_CHART_IDS)

export function isBusinessModuleId(value: unknown): value is BusinessModuleId {
  return typeof value === 'string' && MODULE_ID_SET.has(value)
}

export function isHomeChartId(value: unknown): value is HomeChartId {
  return typeof value === 'string' && HOME_CHART_ID_SET.has(value)
}

export function normalizeEnabledBusinessModules(value: unknown): BusinessModuleId[] {
  if (!Array.isArray(value)) {
    return [...DEFAULT_ENABLED_BUSINESS_MODULES]
  }

  const selected = new Set<BusinessModuleId>()
  for (const item of value) {
    if (isBusinessModuleId(item)) selected.add(item)
  }

  return BUSINESS_MODULE_IDS.filter((id) => selected.has(id))
}

export function normalizeHomeCharts(value: unknown): [HomeChartId, HomeChartId] {
  if (!Array.isArray(value)) {
    return [...DEFAULT_HOME_CHARTS]
  }

  const first = isHomeChartId(value[0]) ? value[0] : DEFAULT_HOME_CHARTS[0]
  const second = isHomeChartId(value[1]) ? value[1] : DEFAULT_HOME_CHARTS[1]
  return [first, second]
}

export function hasBusinessModule(
  enabledModules: readonly BusinessModuleId[] | null | undefined,
  moduleId: BusinessModuleId,
): boolean {
  const enabled = normalizeEnabledBusinessModules(enabledModules)
  return enabled.includes(moduleId)
}

export function isActiveHomeChart(value: HomeChartId): boolean {
  return value !== 'none'
}
