import axios from 'axios'
import { withList } from '../utils/listManager'

export function taxonomiesManager(type) {
    return {
        type,
        showForm: false,
        creating: false,
        deletingId: null,
        form: { name: '', slug: '', description: '', parent_id: '' },
        formMessage: '',
        formError: false,

        ...withList({
            url()         { return `/admin/taxonomies/${this.type}` },
        }),

        async init() { await this.fetch(1) },

        async create() {
            if (!this.form.name.trim()) return
            this.creating = true
            this.formMessage = ''
            try {
                const { data } = await axios.post(`/admin/taxonomies/${this.type}`, this.form, {
                    headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                })
                this.items.unshift(data.term)
                this.meta.total++
                this.form = { name: '', slug: '', description: '', parent_id: '' }
                this.formMessage = data.message
                this.formError = false
                setTimeout(() => this.formMessage = '', 3000)
            } catch (e) {
                this.formMessage = e.response?.data?.message ?? 'Error creating term.'
                this.formError = true
            } finally {
                this.creating = false
            }
        },

        async deleteTerm(id) {
            if (!confirm('Delete this term?')) return
            this.deletingId = id
            try {
                await axios.delete(`/admin/taxonomies/${this.type}/${id}`, {
                    headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                })
                this.items = this.items.filter(t => t.id !== id)
                this.meta.total--
            } catch (e) {
                alert(e.response?.data?.message ?? 'Error deleting term.')
            } finally {
                this.deletingId = null
            }
        },
    }
}
