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

export function postsManager(type) {
    return {
        type,
        status: '',
        deletingId: null,

        ...withList({
            url()         { return `/admin/posts/${this.type}` },
            extraParams() { return { status: this.status } },
        }),

        init() { this.fetch() },

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