import type { Category } from './api/categories'

export const DEFAULT_SUPPLIER_CATEGORIES = [
  'كاميرات',
  'شبكات',
  'أجهزة كومبيوتر',
  'projectors',
  'مقاسم هاتفية',
  'Mobile - Tablet',
  'firewall',
  'طاقة بديلة',
  'حديد',
  'باركود - POS',
  'أجهزة منزلية',
  'تكييف وتبريد',
]

const SUPPLIER_SYSTEM_NAMES = ['Supplier', 'Suppliers']
const SUPPLIER_SYSTEM_AR_NAMES = ['مورد', 'مورّد', 'موردين']

export function normalizeSupplierCategoryName(value?: string | null) {
  return String(value || '').trim().replace(/\s+/g, ' ').toLowerCase()
}

export function isSupplierSystemCategoryName(name?: string | null, nameAr?: string | null) {
  const normalizedName = normalizeSupplierCategoryName(name)
  const normalizedNameAr = normalizeSupplierCategoryName(nameAr)

  return (
    SUPPLIER_SYSTEM_NAMES.map(normalizeSupplierCategoryName).includes(normalizedName) ||
    SUPPLIER_SYSTEM_AR_NAMES.some((word) => normalizedNameAr.includes(normalizeSupplierCategoryName(word)))
  )
}

export function isSupplierBusinessCategoryName(name?: string | null, nameAr?: string | null) {
  const normalizedName = normalizeSupplierCategoryName(name)
  const normalizedNameAr = normalizeSupplierCategoryName(nameAr)
  return DEFAULT_SUPPLIER_CATEGORIES.some((category) => {
    const normalizedCategory = normalizeSupplierCategoryName(category)
    return normalizedName === normalizedCategory || normalizedNameAr === normalizedCategory
  })
}

export function isSupplierOnlyCategoryName(name?: string | null, nameAr?: string | null) {
  return isSupplierSystemCategoryName(name, nameAr) || isSupplierBusinessCategoryName(name, nameAr)
}

export function filterContactCategoryTree(categories: Category[]): Category[] {
  return categories
    .filter((category) => !isSupplierOnlyCategoryName(category.name, category.nameAr))
    .map((category) => ({
      ...category,
      children: category.children ? filterContactCategoryTree(category.children) : undefined,
    }))
}

export function uniqueSupplierCategories(values: Array<string | undefined | null>) {
  const map = new Map<string, string>()
  values.forEach((value) => {
    const label = String(value || '').trim()
    if (!label) return
    const key = normalizeSupplierCategoryName(label)
    if (!map.has(key)) map.set(key, label)
  })
  return Array.from(map.values())
}
