var HuSNS = window.HuSNS || {};
HuSNS.Api = {
    handleResponse: function(response) {
        return new Promise(function(resolve, reject) {
            if (!response || typeof response !== 'object') {
                return reject(new Error('Invalid response'));
            }
            
            if (response.code === undefined) {
                return reject(new Error('Missing response code'));
            }
            
            if (response.code === 1) {
                return resolve(response.data || {});
            }
            
            if (response.code === 401) {
                window.location.href = HuSNS.Url.page('mobile/login');
                return reject(new Error('请先登录'));
            }
            
            return reject(new Error(response.message || '请求失败'));
        });
    },
    
    request: function(options) {
        var defaults = {
            method: 'GET',
            url: '',
            data: {},
            headers: {}
        };
        
        var config = Object.assign({}, defaults, options);
        
        return fetch(config.url, {
            method: config.method,
            headers: config.headers,
            body: config.method === 'POST' || config.method === 'PUT' 
                ? JSON.stringify(config.data) 
                : null,
            credentials: 'include'
        })
        .then(function(res) {
            if (!res.ok) {
                throw new Error('HTTP error ' + res.status);
            }
            return res.json();
        })
        .then(HuSNS.Api.handleResponse);
    }
};

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