import axios from 'axios'

export function pluginsManager() {
    return {
        plugins: [],
        loading: true,
        togglingId: null,

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

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

        async toggle(plugin) {
            this.togglingId = plugin.slug
            const newState = !plugin.is_active
            try {
                await axios.post('/admin/plugins/toggle', {
                    slug: plugin.slug,
                    active: newState ? 1 : 0,
                }, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                plugin.is_active = newState
            } catch (e) {
                alert(e.response?.data?.message ?? 'Error toggling plugin.')
            } finally {
                this.togglingId = null
            }
        },
    }
}
