import axios from 'axios'

export function settingsManager() {
    return {
        saving: false,
        saved: false,
        message: '',

        async submit(event) {
            const form = event.target
            this.saving = true
            this.message = ''
            this.saved = false

            const formData = new FormData(form)

            try {
                const { data } = await axios.post(form.action, formData, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.message = data.message ?? 'Settings saved.'
                this.saved = true
                setTimeout(() => { this.saved = false; this.message = '' }, 3000)
            } catch (e) {
                this.message = e.response?.data?.message ?? 'Error saving settings.'
                this.saved = false
            } finally {
                this.saving = false
            }
        },
    }
}
