// /home/Autopartes/pos/static/js/api.js
// Minimal shared API helper used by standalone pages (e.g. historical_sales).

async function api(path, options = {}) {
    const token = localStorage.getItem('pos_token') || '';
    const url = path.startsWith('http') ? path : path;

    const res = await fetch(url, {
        ...options,
        headers: {
            'Authorization': token ? 'Bearer ' + token : '',
            'Content-Type': 'application/json',
            ...(options.headers || {})
        }
    });

    if (res.status === 401) {
        window.location.href = '/pos/login';
        throw new Error('Sesión expirada');
    }

    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
        throw new Error(data.error || data.message || 'Error ' + res.status);
    }
    return data;
}
