/** Optional modules that can gate customer-dashboard sections. */
export const CUSTOMER_MODULE_IDS = ['customer_products'] as const

export type CustomerModuleId = (typeof CUSTOMER_MODULE_IDS)[number]

/** All optional module ids returned on tenant resolve (business + customer). */
export const BUSINESS_MODULE_IDS = [
  'products',
  'store',
  'portfolio',
  'blog',
  'warehouse',
  'videos',
  ...CUSTOMER_MODULE_IDS,
] as const

export type BusinessModuleId = (typeof BUSINESS_MODULE_IDS)[number]

/** Legacy tenants without modules: business modules on, customer modules opt-in. */
export const DEFAULT_ENABLED_BUSINESS_MODULES: BusinessModuleId[] = [
  'products',
  'store',
  'portfolio',
  'blog',
  'warehouse',
  'videos',
]

const MODULE_ID_SET = new Set<string>(BUSINESS_MODULE_IDS)

export function isBusinessModuleId(value: unknown): value is BusinessModuleId {
  return typeof value === 'string' && MODULE_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 hasBusinessModule(
  enabledModules: readonly BusinessModuleId[] | null | undefined,
  moduleId: BusinessModuleId,
): boolean {
  return normalizeEnabledBusinessModules(enabledModules).includes(moduleId)
}
