// Base
import * as base from './_crud-base'

// Types
import type { Division } from '~/models/division'
import type { TreeItem } from '~/models/_base'

const path = '/api/v1/division'
const name = 'division'

export function create(data: any) {
  return base.create(path, data, name)
}

export function getList(params: any = null) {
  return base.getList(path, params, name)
}

export function getDetail(id: number | string) {
  return base.getDetail(path, id, name)
}

export function update(id: number | string, data: any) {
  return base.update(path, id, data, name)
}

export function remove(id: number | string) {
  return base.remove(path, id, name)
}

export async function getValueLabelList(params: any = null, useCodeAsValue = false): Promise<{ value: string; label: string }[]> {
  let data: { value: string; label: string }[] = []
  const result = await getList(params)
  if (result.success) {
    const resultData = result.body?.data || []
    data = resultData.map((item: Division) => ({
      value: useCodeAsValue ? item.code 
        : item.id ? Number(item.id) 
          : item.code,
      label: item.name,
    }))
  }
  return data
}

/**
 * Convert division response (with childrens) to TreeItem[]
 * @param divisions Array of division objects from API
 * @returns TreeItem[]
 */
export function getValueTreeItems(divisions: any[], byCode = true): TreeItem[] {
  return divisions
    .map((division: Division) => ({
      value: byCode ? String(division.code) 
        : String(division.id) ? String(division.id) 
          : division.code,
      label: division.name,
      hasChildren: Array.isArray(division.childrens) && division.childrens.length > 0,
      children:
        Array.isArray(division.childrens) && division.childrens.length > 0
          ? getValueTreeItems(division.childrens)
          : undefined,
    }))
}
