import { ref } from 'vue'
import { updateDoc } from 'src/api/erp'

/**
 * Composable for inline field editing with optimistic UI.
 * Usage: const { save, saving, error } = useInlineEdit()
 */
export function useInlineEdit () {
  const saving = ref(false)
  const error = ref(null)

  /**
   * Save a single field to ERPNext.
   * @param {string} doctype - e.g. 'Service Location'
   * @param {string} docname - e.g. 'SL-00123'
   * @param {string} field   - e.g. 'city'
   * @param {*}      value   - new value
   * @returns {Promise<boolean>} true if saved successfully
   */
  async function save (doctype, docname, field, value) {
    saving.value = true
    error.value = null
    try {
      await updateDoc(doctype, docname, { [field]: value ?? '' })
      return true
    } catch (e) {
      error.value = e.message || 'Erreur de sauvegarde'
      console.error(`[InlineEdit] Failed to save ${doctype}/${docname}.${field}:`, e)
      // Show notification
      try {
        const { Notify } = await import('quasar')
        Notify?.create?.({
          type: 'negative',
          message: `Erreur: ${field} non sauvegardé`,
          caption: e.message,
          timeout: 3000,
        })
      } catch {}
      return false
    } finally {
      saving.value = false
    }
  }

  return { save, saving, error }
}
