import { ref } from 'vue'
import { toast } from '../utils/toast.js'

// The shared "persist a settings patch" flow for the ML settings cards. Flips a
// busy flag, calls the store's patch (which rethrows on failure), toasts
// success/error, and returns true/false so a toggle handler can revert its
// optimistic switch on failure. Centralises the try/catch/toast the cards each
// hand-rolled (HeadsCard x6, CropProposersCard, MLBackfillCard) — and where the
// threshold-clamp drifted; the clamp now lives in <SettingNumberField>.
//
// Pass the store's patch fn, e.g. useSettingSave(ml.patchSettings).
export function useSettingSave(patchFn) {
  const busy = ref(false)

  // opts.successMessage — toast on success (toggles announce their new state;
  // silent field-saves omit it). opts.errorPrefix — the failure toast prefix
  // ("Could not save" default; toggles used "Could not update").
  async function save(patch, { successMessage = '', errorPrefix = 'Could not save' } = {}) {
    busy.value = true
    try {
      await patchFn(patch)
      if (successMessage) toast({ text: successMessage, type: 'success' })
      return true
    } catch (e) {
      toast({ text: `${errorPrefix}: ${e.message}`, type: 'error' })
      return false
    } finally {
      busy.value = false
    }
  }

  return { busy, save }
}
