import axios from 'axios'

export function menusManager() {
    return {
        menus: [],
        loading: true,
        showCreate: false,
        creating: false,
        deletingId: null,
        newName: '',
        newLocation: '',
        message: '',
        saved: false,

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

        async fetch() {
            this.loading = true
            try {
                const { data } = await axios.get('/admin/menus', {
                    headers: { Accept: 'application/json' },
                })
                this.menus = data.data
            } finally {
                this.loading = false
            }
        },

        async create() {
            if (!this.newName.trim()) return
            this.creating = true
            try {
                const { data } = await axios.post('/admin/menus', {
                    name: this.newName,
                    location: this.newLocation,
                }, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                if (data.redirect) window.location.href = data.redirect
            } catch (e) {
                alert(e.response?.data?.message ?? 'Error creating menu.')
                this.creating = false
            }
        },

        async deleteMenu(id) {
            if (!confirm('Delete this menu?')) return
            this.deletingId = id
            try {
                await axios.delete(`/admin/menus/${id}`, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.menus = this.menus.filter(m => m.id !== id)
            } catch (e) {
                alert(e.response?.data?.message ?? 'Error deleting menu.')
            } finally {
                this.deletingId = null
            }
        },
    }
}
