import axios from 'axios'

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.common['Accept'] = 'application/json'

/**
 * Shared list manager mixin — search + AJAX pagination, no page reload.
 *
 * Usage:
 *   export function myManager() {
 *     return {
 *       ...withList({ url: '/admin/my-resource', extraParams() { return { filter: this.filter } } }),
 *       filter: '',
 *       init() { this.fetch() },
 *       // ... custom methods
 *     }
 *   }
 *
 * The mixin exposes: items, search, meta, loading, fetch(page), onSearch(), pages()
 * Controllers must return: { data: [], meta: { current_page, last_page, total } }
 * OR flat: { data: [], current_page, last_page, total }
 */
export function withList({ url, extraParams = () => ({}) }) {
    return {
        items: [],
        search: '',
        meta: { current_page: 1, last_page: 1, total: 0 },
        loading: false,
        _searchTimer: null,

        async fetch(page = 1) {
            this.loading = true
            try {
                const endpoint = typeof url === 'function' ? url.call(this) : url
                const { data } = await axios.get(endpoint, {
                    params: { page, search: this.search, ...extraParams.call(this) },
                })
                this.items = data.data
                this.meta = data.meta ?? {
                    current_page: data.current_page ?? page,
                    last_page:    data.last_page    ?? 1,
                    total:        data.total        ?? 0,
                }
            } finally {
                this.loading = false
            }
        },

        onSearch() {
            clearTimeout(this._searchTimer)
            this._searchTimer = setTimeout(() => this.fetch(1), 350)
        },

        // Windowed page range: ±2 around current page
        pages() {
            const range = []
            const start = Math.max(1, this.meta.current_page - 2)
            const end   = Math.min(this.meta.last_page, this.meta.current_page + 2)
            for (let i = start; i <= end; i++) range.push(i)
            return range
        },
    }
}
