<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spot.mapper.MemberWalletMapper">

    <!--
        扣减可用余额（三重 WHERE 校验）：
          1. version = #{version}       乐观锁，防并发超扣
          2. balance >= #{amount}       余额下限，防超扣
          3. is_lock = 0                钱包锁定检查
        同时将 version +1，供下次乐观锁使用
    -->
    <update id="deductBalance">
        UPDATE member_wallet
        SET balance = balance - #{amount},
            version = version + 1
        WHERE member_id = #{memberId}
          AND coin_id   = #{coinId}
          AND version   = #{version}
          AND balance   >= #{amount}
          AND is_lock   = 0
    </update>

    <!-- 初始化资金钱包（INSERT IGNORE：钱包已存在时静默跳过，并发安全） -->
    <insert id="insertOrIgnore">
        INSERT IGNORE INTO member_wallet (member_id, coin_id, balance, frozen_balance, to_released, is_lock, version)
        VALUES (#{memberId}, #{coinId}, 0, 0, 0, 0, 0)
    </insert>

    <!-- 增加可用余额（含锁定校验） -->
    <update id="addBalance">
        UPDATE member_wallet
        SET balance = balance + #{amount}
        WHERE member_id = #{memberId}
          AND coin_id   = #{coinId}
          AND is_lock   = 0
    </update>

</mapper>
