import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import { useAp2iRequestService } from '~/composables/data/useAp2iRequestService'
import UrlUtils from '~/services/utils/urlUtils'

/**
 * @category composables/form
 * Composable pour des utils de verifications
 */
export function useValidation() {
  /**
   * Use méthode fournissant une fonction pour tester la validité d'un Siret ainsi que la gestion du message d'erreur
   */
  function useValidateSiret() {
    const siretError: Ref<boolean> = ref(false)
    const siretErrorMessage: Ref<string> = ref('')

    const validateSiret = async (siret: string) => {
      const { apiRequestService } = useAp2iRequestService()
      const response: Response = await apiRequestService.get(
        UrlUtils.join('/api/siret-checking', siret),
      )

      if (typeof response === 'undefined') {
        siretError.value = false
        siretErrorMessage.value = ''
      }

      if (!Object.prototype.hasOwnProperty.call(response, 'isCorrect')) {
        throw new Error('Invalid response format')
      }

      // @ts-expect-error At this point, response has an 'isCorrect' property
      const isCorrect = response.isCorrect

      const i18n = useI18n()
      siretError.value = !isCorrect
      siretErrorMessage.value = isCorrect
        ? ''
        : (i18n.t('siret_error') as string)
    }

    return {
      siretError,
      siretErrorMessage,
      validateSiret,
    }
  }

  return {
    useValidateSiret,
  }
}
