import { computed, ref } from 'vue'
import type { KbxProblem, KbxValidationError } from '@kbx/contracts'

export function useKbxValidation() {
  const errors = ref<KbxValidationError[]>([])

  const fieldErrors = computed(() => {
    const result = new Map<string, string>()
    for (const error of errors.value) {
      if (error.field && !error.rowKey && !result.has(error.field)) result.set(error.field, error.message)
    }
    return result
  })

  function fieldError(field: string) {
    return fieldErrors.value.get(field)
  }

  function setErrors(next: KbxValidationError[]) {
    errors.value = next
  }

  function setRowFieldError(rowKey: string, field: string, error?: Omit<KbxValidationError, 'rowKey' | 'field'>) {
    errors.value = errors.value.filter(x => !(x.rowKey === rowKey && x.field === field))
    if (error) errors.value.push({ rowKey, field, ...error })
  }

  function applyProblem(problem: KbxProblem) {
    errors.value = problem.type === 'validation' ? problem.errors : []
  }

  function clear() {
    errors.value = []
  }

  return { errors, fieldError, setErrors, setRowFieldError, applyProblem, clear }
}
