import toCamel from 'camelcase-keys'

import { isApiError } from '@/lib/api'

export type FieldErrors<T extends string = string> = Partial<Record<T, string[]>>

export type ValidationError<T extends string = string> =
    { message:      string
      fieldErrors:  FieldErrors<T>
      baseErrors:   string[] }

type RawValidationError = { type?:        string
			    message?:     string
			    errors?:      Record<string, string[]>
			    baseErrors?:  string[] }


export const extractValidationError = <T extends string = string> (err: unknown) => {
  if (!(isApiError (err)) || err.response?.status !== 422)
    return null

  const rawData = toCamel ((err.response.data ?? { }) as Record<string, unknown>,
			   { deep: true }) as RawValidationError
  const data: RawValidationError = {
      type:       rawData.type as string | undefined,
      message:    rawData.message as string | undefined,
      errors:     rawData.errors as Record<string, string[]> | undefined,
      baseErrors: rawData.baseErrors as string[] | undefined }

  if (data.type !== 'validation_error' && !(data.errors))
    return null

  return { message: data.message ?? '入力内容を確認してください．',
	   fieldErrors: (data.errors ?? { }) as FieldErrors<T>,
	   baseErrors: data.baseErrors ?? [] }
}
