import pool from '../config/db.js';

export class RpcService {
    static async executeFunction(functionName, body) {
        if (functionName === 'increment-customer-balance') {
            await pool.execute('UPDATE customers SET account_balance = account_balance + ? WHERE id = ?', [body.amount, body.customerId]);
        } else if (functionName === 'update-supplier-balance') {
            await pool.execute('UPDATE suppliers SET current_balance = current_balance + ? WHERE id = ?', [body.amount, body.supplierId]);
        } else if (functionName === 'update-customer-stats') {
            await pool.execute('UPDATE customers SET total_spent = total_spent + ?, total_orders = total_orders + ? WHERE id = ?', [body.amount, body.ordersAdded, body.customerId]);
        } else if (functionName === 'decrement-paper-stock') {
            await pool.execute('UPDATE paper_types SET in_stock = in_stock - ? WHERE id = ?', [body.amount, body.paperTypeId]);
        } else if (functionName === 'create-journal-entry') {
            const { description, date, journalId, lines } = body;
            if (lines && Array.isArray(lines)) {
                for (const line of lines) {
                    const [[{ uuid }]] = await pool.execute('SELECT UUID() as uuid');
                    await pool.execute(
                        'INSERT INTO accounting_entries (id, date, description, account_id, amount, type, reference) VALUES (?, ?, ?, ?, ?, ?, ?)',
                        [ uuid, date || new Date().toISOString(), line.description || description, line.accountId, line.debit > 0 ? line.debit : line.credit, line.debit > 0 ? 'debit' : 'credit', journalId || null ]
                    );
                }
            }
        } else {
            throw new Error(`RPC Function ${functionName} not found`);
        }
    }
}
