import axios from 'axios'

export function postForm(options = {}) {
    return {
        saving: false,
        saved: false,
        errors: {},
        message: '',

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

            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 ?? 'Saved.'
                this.saved = true

                // Hard redirect if server says so
                if (data.redirect) {
                    window.location.href = data.redirect
                    return
                }

                // Soft URL update for create → edit
                if (data.edit_url && window.location.href !== data.edit_url) {
                    history.replaceState(null, '', data.edit_url)
                    const methodInput = form.querySelector('input[name="_method"]')
                    if (!methodInput) {
                        const hidden = document.createElement('input')
                        hidden.type = 'hidden'
                        hidden.name = '_method'
                        hidden.value = 'PUT'
                        form.appendChild(hidden)
                    }
                    form.action = data.edit_url
                }

                setTimeout(() => { this.saved = false; this.message = '' }, 3000)
            } catch (err) {
                if (err.response?.status === 422) {
                    this.errors = err.response.data.errors ?? {}
                    const msgs = Object.values(this.errors).flat()
                    this.message = msgs.length ? msgs.join(' · ') : 'Please fix the errors below.'
                } else {
                    this.message = err.response?.data?.message ?? 'An error occurred.'
                }
            } finally {
                this.saving = false
            }
        },

        hasError(field) {
            return !!this.errors[field]
        },

        getError(field) {
            return this.errors[field]?.[0] ?? ''
        },
    }
}
