const db = require('../../plugin/DataBase/db')

function normalizeResult(rawResult) {
    if (Array.isArray(rawResult)) return rawResult[0]
    return rawResult
}

async function executeSql(executor, sql, params) {
    if (executor && typeof executor.execute === 'function') {
        return executor.execute(sql, params)
    }
    return db.query(sql, params)
}

async function insertLedgerRecord({
    executor,
    userUuid,
    delta,
    balanceBefore,
    balanceAfter,
    bizType,
    bizId,
    operatorUuid = null,
    remark = ''
}) {
    if (!userUuid || !bizType) return false

    const result = await executeSql(
        executor,
        `INSERT IGNORE INTO lepao_count_ledger
        (user_uuid, delta, balance_before, balance_after, biz_type, biz_id, operator_uuid, remark, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
        [
            userUuid,
            Number(delta || 0),
            Number(balanceBefore || 0),
            Number(balanceAfter || 0),
            bizType,
            String(bizId || ''),
            operatorUuid,
            String(remark || '')
        ]
    )

    const rows = normalizeResult(result)
    return !!rows && Number(rows.affectedRows || 0) > 0
}

module.exports = { insertLedgerRecord }
