/* API layer ----------------------------------------------------------------
   Thin wrapper over axios that mirrors the Inspector backend conventions:
   - cookie auth (withCredentials)
   - antiforgery header on every mutating request
   - DevExtreme-style loadOptions ({ skip, take, requireTotalCount, ... })
   - transparent mock fallback while APP_CONFIG.useMock is true
--------------------------------------------------------------------------- */
window.API = (function () {
    var cfg = window.APP_CONFIG;

    var http = axios.create({
        baseURL: cfg.apiBase || '',
        withCredentials: true,
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    });

    var csrfToken = null;

    async function ensureCsrf() {
        if (csrfToken || cfg.useMock) return csrfToken;
        try {
            var res = await http.get(cfg.csrfUrl);
            var t = res.data;
            csrfToken = (t && typeof t === 'object') ? (t.token || t.Token || t.value) : t;
            if (csrfToken) http.defaults.headers.common[cfg.csrfHeader] = csrfToken;
        } catch (e) { /* login page etc. — ignore, request will 401 */ }
        return csrfToken;
    }

    /* Redirect to backend login on auth failure. */
    http.interceptors.response.use(
        function (r) { return r; },
        function (err) {
            var s = err && err.response && err.response.status;
            if (s === 401 || s === 403) {
                if (!cfg.useMock) window.location.href = (cfg.apiBase || '') + '/Account/Login';
            }
            return Promise.reject(err);
        }
    );

    function delay(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }

    /* Load a DevExtreme-backed list. Returns { items, total }. */
    async function load(key, opts) {
        opts = opts || {};
        var ep = window.ENDPOINTS[key];

        if (cfg.useMock) {
            await delay(280 + Math.random() * 260);            // simulate latency
            return window.MOCK.list(key, opts);
        }

        await ensureCsrf();
        var loadOptions = {
            skip: opts.skip || 0,
            take: opts.take || 25,
            requireTotalCount: true,
            sort: opts.sort || null,
            filter: opts.filter || null,
            FilterData: opts.filterData || {}
        };

        var url = ep.url;
        if (opts.query) url += (url.indexOf('?') < 0 ? '?' : '&') + toQuery(opts.query);

        var res = ep.method === 'get'
            ? await http.get(url, { params: opts.query })
            : await http.post(url, loadOptions);

        var d = res.data || {};
        return { items: d.data || d.Data || (Array.isArray(d) ? d : []), total: d.totalCount != null ? d.totalCount : (d.TotalCount || 0) };
    }

    async function get(url, params) {
        if (cfg.useMock) { await delay(220); return window.MOCK.get(url, params); }
        await ensureCsrf();
        var res = await http.get(url, { params: params });
        return res.data;
    }

    async function post(url, body) {
        if (cfg.useMock) { await delay(300); return { isSuccess: true, mock: true }; }
        await ensureCsrf();
        var res = await http.post(url, body);
        return res.data;
    }

    function toQuery(obj) {
        return Object.keys(obj).map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]); }).join('&');
    }

    return { load: load, get: get, post: post, ensureCsrf: ensureCsrf, http: http };
})();
