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

export function usersManager() {
    return {
        deletingId: null,

        ...withList({ url: '/admin/users' }),

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

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