/**
 * NEXUS IT — API Client
 */
const API_BASE = '/api/v1';

const NexusAPI = {
    getToken() {
        return localStorage.getItem('nexus_token');
    },

    async request(endpoint, options = {}) {
        const url = API_BASE + endpoint;
        const headers = { 'Content-Type': 'application/json', ...options.headers };
        const token = this.getToken();
        if (token) headers['Authorization'] = 'Bearer ' + token;

        try {
            const res = await fetch(url, { ...options, headers });
            
            if (res.status === 401) {
                localStorage.removeItem('nexus_token');
                localStorage.removeItem('nexus_user');
                window.location.href = '/app/';
                return { success: false, message: 'Sesión expirada' };
            }

            const data = await res.json();
            return data;
        } catch (e) {
            console.error('API Error:', e);
            return { success: false, message: 'Error de conexión' };
        }
    },

    async get(endpoint) {
        return this.request(endpoint, { method: 'GET' });
    },

    async post(endpoint, body) {
        return this.request(endpoint, { method: 'POST', body: JSON.stringify(body) });
    },

    async put(endpoint, body) {
        return this.request(endpoint, { method: 'PUT', body: JSON.stringify(body) });
    },

    async delete(endpoint) {
        return this.request(endpoint, { method: 'DELETE' });
    },

    async upload(endpoint, formData) {
        const token = this.getToken();
        const headers = {};
        if (token) headers['Authorization'] = 'Bearer ' + token;
        
        try {
            const res = await fetch(API_BASE + endpoint, { method: 'POST', headers, body: formData });
            return await res.json();
        } catch (e) {
            return { success: false, message: 'Error al subir archivo' };
        }
    }
};

window.NexusAPI = NexusAPI;
