var HuSNS = window.HuSNS || {};
HuSNS.Request = {
    _baseUrl: window.API_BASE_URL || '',
    
    get: function(url, params) {
        var fullUrl = this._buildUrl(url, params);
        return this._fetch(fullUrl, { method: 'GET' });
    },
    
    post: function(url, data) {
        var fullUrl = this._baseUrl + url;
        return this._fetch(fullUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    },
    
    put: function(url, data) {
        var fullUrl = this._baseUrl + url;
        return this._fetch(fullUrl, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    },
    
    delete: function(url, params) {
        var fullUrl = this._buildUrl(url, params);
        return this._fetch(fullUrl, { method: 'DELETE' });
    },
    
    _buildUrl: function(url, params) {
        var fullUrl = this._baseUrl + url;
        if (params && typeof params === 'object') {
            var queryString = new URLSearchParams(params).toString();
            if (queryString) {
                fullUrl += (fullUrl.indexOf('?') === -1 ? '?' : '&') + queryString;
            }
        }
        return fullUrl;
    },
    
    _fetch: function(url, options) {
        return fetch(url, options)
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('HTTP error ' + response.status);
                }
                return response.text();
            })
            .then(function(text) {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    throw new Error('Invalid JSON response');
                }
            })
            .then(function(data) {
                if (data.code !== 1) {
                    throw new Error(data.message || '请求失败');
                }
                return data.data || data;
            });
    }
};

if (typeof module !== 'undefined' && module.exports) {
    module.exports = HuSNS.Request;
}