import  {useI18n} from 'vue-i18n'
import {useAp2iRequestService} from "~/composables/data/useAp2iRequestService";
import UrlUtils from "~/services/utils/urlUtils";
import {Ref} from "@vue/reactivity";

/**
 * @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: any = await apiRequestService.get(UrlUtils.join('/api/siret-checking', siret))

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

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

    return {
      siretError,
      siretErrorMessage,
      validateSiret
    }
  }

  function useValidateSubdomain() {
    const isSubdomainAvailable = async (subdomain: string | null): Promise<boolean> => {
      if (subdomain === null) {
        return true
      }

      const { apiRequestService } = useAp2iRequestService()
      const response: any = await apiRequestService.get('/api/subdomains', {'subdomain': subdomain})

      return typeof response !== 'undefined' && response.metadata.totalItems === 0
    }
    return {
      isSubdomainAvailable
    }
  }

  return {
    useValidateSiret,
    useValidateSubdomain
  }
}
