// api.js - Módulo de Serviço de Dados (VERSÃO CORRIGIDA E LIMPA)

// !!! ATENÇÃO !!! Verifique se esta é a URL da sua implantação
const API_URL = "https://dualx.vfsolucoes.com.br/index.php";

/**
 * Função utilitária para fazer chamadas à API.
 * @param {string} action - A ação a ser executada.
 * @param {object} payload - Os dados a serem enviados.
 * @param {string} [userRole] - O papel do usuário logado.
 * @returns {Promise<object>}
 */
export async function callApi(action, payload, userRole = null) {
    const formData = new FormData();
    formData.append('action', action);
    for (const key in payload) {
        if (Object.prototype.hasOwnProperty.call(payload, key)) {
            formData.append(key, payload[key]);
        }
    }
    if (userRole) {
        formData.append('userRole', userRole);
    }

    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            let errorMessage = `Erro na comunicação (${response.status} ${response.statusText}).`;
            try {
                const errorBody = await response.json();
                if (errorBody && errorBody.message) {
                    errorMessage = errorBody.message;
                }
            } catch (jsonError) {
                // Ignore
            }
            throw new Error(errorMessage);
        }
        
        const result = await response.json();

        if (result.status === 'error') {
            throw new Error(result.message || 'Ocorreu um erro desconhecido na API.');
        }
        return result;

    } catch (error) {
        console.error('Erro na chamada à API:', error);
        throw error;
    }
}

// Módulo de serviço de dados para o front-end
export const DataService = {
    // Login / Usuários
    loginUser: async (email, password) => callApi('USER_LOGIN', { email, password }),
    getUsers: async (userRole) => callApi('GET_USERS', {}, userRole),
    addUser: async (user, userRole) => callApi('ADD_USER', user, userRole),
    changeUserPassword: async (payload, userRole) => callApi('CHANGE_PASSWORD', payload, userRole),
    redefinePassword: async (payload, role) => callApi('REDEFINE_PASSWORD', payload, role),
    checkUserExistsByEmail: async (payload) => callApi('CHECK_EMAIL_EXISTS', payload, 'public'),
    updatePasswordByEmail: async (payload) => callApi('UPDATE_PASSWORD_BY_EMAIL', payload, 'public'),
    updateUserRole: async (payload, userRole) => callApi('UPDATE_USER_ROLE', payload, userRole),

    // Produtos e Estoque Principal
    getProductsInfo: async (userRole) => callApi('GET_PRODUCTS_INFO', {}, userRole),
    addProductDefinition: async (product, userRole) => callApi('ADD_PRODUCT_DEFINITION', product, userRole),
    getProductsSummary: async (userRole) => callApi('GET_PRODUCTS_SUMMARY', {}, userRole),
    getInventory: async (userRole) => callApi('GET_INVENTORY', {}, userRole),
    addInventoryItem: async (item, userRole) => callApi('ADD_INVENTORY_ITEM', item, userRole),
    getAllStockDefinitions: (userRole) => callApi('GET_ALL_STOCK_DEFINITIONS', {}, userRole),
    updateSafetyStock: (payload, userRole) => callApi('UPDATE_SAFETY_STOCK', payload, userRole),
    editarItemEstoque: async (payload, userRole) => callApi('EDITAR_ITEM_ESTOQUE', payload, userRole), // <--- LINHA ADICIONADA
    
    // Veículos
    getVehicles: (userRole) => callApi('GET_VEHICLES', {}, userRole),
    getAllVehicleInventories: async (userRole) => callApi('GET_ALL_VEHICLE_INVENTORIES', {}, userRole),
    addItemToVehicle: async (item, userRole) => callApi('ADD_ITEM_TO_VEHICLE', item, userRole),
    removeItemFromVehicle: async (item, userRole) => callApi('REMOVE_ITEM_FROM_VEHICLE', item, userRole),

    // Torres e Setores
    getTowers: async (userRole) => callApi('GET_TOWERS', {}, userRole),
    addTorre: async (payload, userRole) => callApi('ADD_TORRE', payload, userRole),
    alocarItemTorre: async (payload, userRole) => callApi('ALOCAR_ITEM_TORRE', payload, userRole),
    retirarItemTorre: async (payload, userRole) => callApi('RETIRAR_ITEM_TORRE', payload, userRole),
    getTowerHistory: async (payload, userRole) => callApi('GET_TOWER_HISTORY', payload, userRole),
    addTowerObservation: async (payload, userRole) => callApi('ADD_TOWER_OBSERVATION', payload, userRole),
    addSectorToTower: async (payload, userRole) => callApi('ADD_SECTOR_TO_TOWER', payload, userRole),
    updateSectorLimit: async (payload, userRole) => callApi('UPDATE_SECTOR_LIMIT', payload, userRole),
    getSectorClientCounts: async (userRole) => callApi('GET_SECTOR_CLIENT_COUNTS', {}, userRole),

    // Clientes e Atividades
    getClients: async (userRole) => callApi('GET_CLIENTS', {}, userRole),
    addClient: async (client, userRole) => callApi('ADD_CLIENT', client, userRole),
    updateClient: async (payload, userRole) => callApi('UPDATE_CLIENT', payload, userRole),
    getClientActivities: async (userRole) => callApi('GET_CLIENT_ACTIVITIES', {}, userRole),
    addClientActivity: async (activity, userRole) => callApi('ADD_CLIENT_ACTIVITY', activity, userRole),
    getClientActivityDetails: async (userRole) => callApi('GET_CLIENT_ACTIVITY_DETAILS', {}, userRole),
    getClientActivitySummary: async (payload, userRole) => callApi('GET_CLIENT_ACTIVITY_SUMMARY', payload, userRole),

    // Redirecionamento e Retífica
    getRedirectInventory: async (userRole) => callApi('GET_REDIRECT_INVENTORY', {}, userRole),
    redirectItem: async (item, userRole) => callApi('REDIRECT_ITEM', item, userRole),
    getRectificationItems: async (userRole) => callApi('GET_RECTIFICATION_ITEMS', {}, userRole),
    addItemToRectification: async (item, userRole) => callApi('ADD_ITEM_TO_RECTIFICATION', item, userRole),
    removeItemFromRectification: async (item, userRole) => callApi('REMOVE_ITEM_FROM_RECTIFICATION', item, userRole),

    // Logs e Transações
    getTransactionLogs: async (userRole) => callApi('GET_TRANSACTION_LOGS', {}, userRole),
    logTransaction: async (log, userRole) => callApi('LOG_TRANSACTION', log, userRole),

    // Consumíveis
    getItensConsumiveis: async (userRole) => callApi('GET_ITENS_CONSUMIVEIS', {}, userRole),
    addItemConsumivel: async (itemData, userRole) => callApi('ADD_ITEM_CONSUMIVEL', itemData, userRole),
    getHistoricoConsumo: async (datePayload, userRole) => callApi('GET_HISTORICO_CONSUMO', datePayload, userRole),
    registrarConsumo: async (consumoData, userRole) => callApi('REGISTRAR_CONSUMO', consumoData, userRole),
    recarregarItemConsumivel: async (payload, userRole) => callApi('RECARREGAR_ITEM_CONSUMIVEL', payload, userRole),
    getConsumptionLogCount: async (userRole) => callApi('GET_CONSUMPTION_LOG_COUNT', {}, userRole),
    updateConsumableSafetyStock: (payload, userRole) => callApi('UPDATE_CONSUMABLE_SAFETY_STOCK', payload, userRole),
    transferConsumableToVehicle: async (payload, userRole) => callApi('TRANSFER_CONSUMABLE_TO_VEHICLE', payload, userRole),

    // Combustível
    addAbastecimento: async (payload, userRole) => callApi('ADD_ABASTECIMENTO', payload, userRole),
    getHistoricoCombustivel: async (userRole) => callApi('GET_HISTORICO_COMBUSTIVEL', {}, userRole),
    getMonthlyFuelReport: async (datePayload, userRole) => callApi('GET_MONTHLY_FUEL_REPORT', datePayload, userRole),

    // Financeiro
    getPendingFinancial: async () => callApi('GET_PENDING_FINANCIAL', {}),
    finalizeBilling: async (payload) => callApi('FINALIZE_BILLING', payload),
    getBilledActivities: async () => callApi('GET_BILLED_ACTIVITIES', {}),

    // Mensagens
    getMessageTemplates: async (userRole) => callApi('GET_MESSAGE_TEMPLATES', {}, userRole),
    saveMessageTemplate: async (payload, userRole) => callApi('SAVE_MESSAGE_TEMPLATE', payload, userRole),

    // Configurações
    getConfiguracao: async (payload, userRole) => callApi('GET_CONFIGURACAO', payload, userRole),
    updateConfiguracao: async (payload, userRole) => callApi('UPDATE_CONFIGURACAO', payload, userRole),
    getAppConfig: async () => callApi('GET_APP_CONFIG', {}),
    getVersionInfo: async () => callApi('GET_VERSION_INFO', {}),

    // ==========================================
    // NOVAS FUNÇÕES DE EXCLUSÃO (DELETAR DO BANCO)
    // ==========================================
    excluirTorre: async (torreId, userRole) => {
        return callApi('EXCLUIR_TORRE', { torreId: torreId }, userRole);
    },
    excluirSetor: async (setorId, userRole) => {
        return callApi('EXCLUIR_SETOR', { setorId: setorId }, userRole);
    },
    excluirItemDefinitivo: async (payload, userRole) => {
        return callApi('EXCLUIR_ITEM_DEFINITIVO', payload, userRole);
    },
    excluirUsuario: async (userId, userRole) => {
        return callApi('EXCLUIR_USUARIO', { userId: userId }, userRole);
    }
};