import axios from 'axios'

export function contentTypesManager() {
    return {
        types: [],
        loading: true,
        deletingId: null,

        builtins: [
            { slug: 'post', name: 'Post', icon: 'document-text' },
            { slug: 'page', name: 'Page', icon: 'document' },
        ],

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

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

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