import type { ColumnGroupType, ColumnType, ColumnsType } from 'antd/es/table'

const NUM_TITLE =
  /금액|합계|건수|수량|마진|단가|월정액|입금|출금|인센티브|차감금|차감(?!일)|정책합산|정산금|매출|가격|원가|수수료|리베이트|잔액|합산|횟수|접속수|발송(?!일)|개월|할인(?!율)|개통금액|실정산/

const NUM_INDEX =
  /^(?:.*(?:amount|price|margin|sum|count|fee|deposit|withdraw|incentive|qty|quantity|months|deduct|settle|policySum|cash|card|total|loginCount|rate).*)$/i

const SKIP_TITLE =
  /연락처|계좌|아이디|비밀번호|전화|휴대폰|주소|메모|비고|내용|제목|고객명|성명|이름|업체|상품|모델|상태|구분|분류|유형|권한|직원|거래처|일시|일자|날짜|등록일|처리일/

const SKIP_INDEX =
  /bankAccount|account|phone|password|userid|name|address|memo|title|content|status|type|date|at$/i

function titleText(title: ColumnType<unknown>['title']): string {
  if (typeof title === 'string' || typeof title === 'number') return String(title)
  return ''
}

function isNumericColumn<T>(col: ColumnType<T>): boolean {
  if (col.align === 'right') return true
  const title = titleText(col.title as ColumnType<unknown>['title'])
  const dataIndex = Array.isArray(col.dataIndex)
    ? col.dataIndex.map(String).join('.')
    : col.dataIndex == null
      ? ''
      : String(col.dataIndex)

  if (title && SKIP_TITLE.test(title)) return false
  if (dataIndex && SKIP_INDEX.test(dataIndex)) return false
  if (title && NUM_TITLE.test(title)) return true
  if (dataIndex && NUM_INDEX.test(dataIndex)) return true
  return false
}

function mergeClass(base: string | undefined, extra: string): string {
  return [base, extra].filter(Boolean).join(' ')
}

function isGroup<T>(col: ColumnType<T> | ColumnGroupType<T>): col is ColumnGroupType<T> {
  return Array.isArray((col as ColumnGroupType<T>).children)
}

function normalizeOne<T>(col: ColumnType<T> | ColumnGroupType<T>): ColumnType<T> | ColumnGroupType<T> {
  if (isGroup(col)) {
    return {
      ...col,
      align: 'center',
      children: col.children.map((c) => normalizeOne(c)),
    }
  }

  const numeric = isNumericColumn(col)
  return {
    ...col,
    align: numeric ? 'right' : 'center',
    className: numeric ? mergeClass(col.className, 'table-col-num') : col.className,
  }
}

/** 목록 테이블: 헤더·일반 텍스트 중앙, 숫자/금액 우측 */
export function normalizeTableColumns<T>(columns?: ColumnsType<T>): ColumnsType<T> | undefined {
  if (!columns) return columns
  return columns.map((col) => normalizeOne(col))
}
