import { useState } from 'react'

import { extractValidationError } from '@/lib/apiErrors'

import type { FieldErrors } from '@/lib/apiErrors'


export const useValidationErrors = <T extends string> () => {
  const [baseErrors, setBaseErrors] = useState<string[]> ([])
  const [fieldErrors, setFieldErrors] = useState<FieldErrors<T>> ({ })

  const clearValidationErrors = () => {
    setBaseErrors ([])
    setFieldErrors ({ })
  }

  const applyValidationError = (error: unknown): boolean => {
    const validationError = extractValidationError<T> (error)
    if (!(validationError))
      return false

    setBaseErrors (validationError.baseErrors)
    setFieldErrors (validationError.fieldErrors)
    return true
  }

  return { baseErrors, fieldErrors, clearValidationErrors, applyValidationError }
}
