import { api, apiURL } from '@Services/Api';

/**
 * Servicio para gestionar cajas registradoras
 */
const cashRegisterService = {
    /**
     * Helper para extraer datos del registro de diferentes formatos de respuesta
     */
    extractRegisterData(response) {
        const register = response.register || 
                        response.cashRegister || 
                        response.cash_register || 
                        response.model || 
                        response;
        
        // Mapear campos del backend a nombres esperados por el frontend
        if (response.total_sales !== undefined) {
            register.total_sales = response.total_sales;
        }
        if (response.total_cash !== undefined) {
            register.cash_sales = response.total_cash;
        }
        if (response.sales_count !== undefined) {
            register.transaction_count = response.sales_count;
        }
        
        // Calcular card_sales sumando credit_card + debit_card
        const creditCard = parseFloat(response.total_credit_card || 0);
        const debitCard = parseFloat(response.total_debit_card || 0);
        if (creditCard > 0 || debitCard > 0) {
            register.card_sales = creditCard + debitCard;
        }
        
        // Mantener payment_summary si existe
        if (response.payment_summary) {
            register.payment_summary = response.payment_summary;
        }
        
        return register;
    },

    /**
     * Abrir una nueva caja registradora
     * @param {Number} initialCash - Monto inicial en efectivo
     * @returns {Promise}
     */
    async openCashRegister(initialCash) {
        return new Promise((resolve, reject) => {
            api.post(apiURL('cash-registers/open'), {
                data: { initial_cash: initialCash },
                onSuccess: (response) => resolve(this.extractRegisterData(response)),
                onError: reject
            });
        });
    },

    /**
     * Obtener la caja registradora actualmente abierta
     * @returns {Promise}
     */
    async getCurrentCashRegister() {
        return new Promise((resolve, reject) => {
            api.get(apiURL('cash-registers/current'), {
                onSuccess: (response) => {
                    resolve(this.extractRegisterData(response));
                },
                onError: (error) => {
                    // Si es 404, significa que no hay caja abierta (no es un error)
                    if (error.status === 404 || error.response?.status === 404) {
                        resolve(null);
                    } else {
                        reject(error);
                    }
                }
            });
        });
    },

    /**
     * Cerrar una caja registradora con el corte de caja
     * @param {Number} id - ID de la caja registradora
     * @param {Object} closeData - Datos del cierre (final_cash, notes, etc.)
     * @returns {Promise}
     */
    async closeCashRegister(id, closeData) {
        return new Promise((resolve, reject) => {
            api.put(apiURL(`cash-registers/${id}/close`), {
                data: closeData,
                onSuccess: (response) => resolve(this.extractRegisterData(response)),
                onError: reject
            });
        });
    },

    /**
     * Obtener historial de cajas registradoras
     * @param {Object} filters - Filtros de búsqueda (fecha, usuario, etc.)
     * @returns {Promise}
     */
    async getCashRegisterHistory(filters = {}) {
        return new Promise((resolve, reject) => {
            api.get(apiURL('cash-registers'), {
                params: filters,
                onSuccess: (response) => {
                    const registers = response.registers || response.cashRegisters || response.cash_registers || response;
                    
                    // Mapear cada registro en el historial
                    if (registers.data && Array.isArray(registers.data)) {
                        registers.data = registers.data.map(reg => this.extractRegisterData({
                            register: reg,
                            sales_count: reg.sales_count,
                            total_sales: reg.total_sales,
                            total_cash: reg.total_cash,
                            total_credit_card: reg.total_credit_card,
                            total_debit_card: reg.total_debit_card,
                            payment_summary: reg.payment_summary
                        }));
                    } else if (Array.isArray(registers)) {
                        return resolve(registers.map(reg => this.extractRegisterData({
                            register: reg,
                            sales_count: reg.sales_count,
                            total_sales: reg.total_sales,
                            total_cash: reg.total_cash,
                            total_credit_card: reg.total_credit_card,
                            total_debit_card: reg.total_debit_card,
                            payment_summary: reg.payment_summary
                        })));
                    }
                    
                    resolve(registers);
                },
                onError: reject
            });
        });
    },

    /**
     * Obtener detalle de una caja registradora específica
     * @param {Number} id - ID de la caja registradora
     * @returns {Promise}
     */
    async getCashRegisterDetail(id) {
        return new Promise((resolve, reject) => {
            api.get(apiURL(`cash-registers/${id}`), {
                onSuccess: (response) => resolve(this.extractRegisterData(response)),
                onError: reject
            });
        });
    }
};

export default cashRegisterService;
