import { ref, nextTick } from 'vue'
import { sendOTP as apiSendOTP, verifyOTP as apiVerifyOTP } from 'src/api/catalog'
import { normalizePhone } from 'src/utils/format'

export function useOTP (form, { onVerified } = {}) {
  const inputRef = ref(null)
  const identifier = ref('')
  const step = ref('idle') // idle | verify
  const code = ref('')
  const sending = ref(false)
  const verifying = ref(false)
  const verified = ref(false)
  const channel = ref('')
  const error = ref('')
  const addresses = ref([])

  async function send () {
    sending.value = true
    error.value = ''
    try {
      const result = await apiSendOTP(identifier.value)
      if (!result.found) {
        error.value = 'Aucun compte trouvé avec cet identifiant.'
        return false
      }
      step.value = 'verify'
      channel.value = result.channel
      nextTick(() => inputRef.value?.focus())
      return true
    } catch (e) {
      error.value = e.message || 'Erreur'
      return false
    } finally { sending.value = false }
  }

  async function verify () {
    verifying.value = true
    error.value = ''
    try {
      const result = await apiVerifyOTP(identifier.value, code.value)
      if (!result.valid) {
        error.value = result.reason === 'expired' ? 'Code expiré. Renvoyez un nouveau code.'
          : result.reason === 'wrong_code' ? 'Code invalide. Vérifiez et réessayez.'
          : 'Vérification échouée.'
        return false
      }
      verified.value = true
      form.customer_id = result.customer_id
      form.name = result.customer_name || form.name
      if (result.phone) form.phone = normalizePhone(result.phone)
      if (result.email) form.email = result.email
      else if (identifier.value.includes('@')) form.email = identifier.value
      if (result.addresses?.length) addresses.value = result.addresses
      onVerified?.(result)
      return true
    } catch (e) {
      error.value = e.message || 'Erreur'
      return false
    } finally { verifying.value = false }
  }

  function reset () {
    step.value = 'idle'
    code.value = ''
    verified.value = false
    error.value = ''
    addresses.value = []
    form.customer_id = null
  }

  return { inputRef, identifier, step, code, sending, verifying, verified, channel, error, addresses, send, verify, reset }
}
