<?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.dora.mapper.UserBalanceLogMapper">

    <resultMap id="UserBalanceLogResultMap" type="com.dora.entity.UserBalanceLog">
        <id column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="change_type" property="changeType"/>
        <result column="change_amount" property="changeAmount"/>
        <result column="balance_before" property="balanceBefore"/>
        <result column="balance_after" property="balanceAfter"/>
        <result column="source_type" property="sourceType"/>
        <result column="source_id" property="sourceId"/>
        <result column="description" property="description"/>
        <result column="create_time" property="createTime"/>
        <result column="is_deleted" property="isDeleted"/>
    </resultMap>

    <insert id="insert" parameterType="com.dora.entity.UserBalanceLog" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user_balance_log (
            user_id, change_type, change_amount, balance_before, balance_after,
            source_type, source_id, description, create_time, is_deleted
        ) VALUES (
            #{userId}, #{changeType}, #{changeAmount}, #{balanceBefore}, #{balanceAfter},
            #{sourceType}, #{sourceId}, #{description}, NOW(), 0
        )
    </insert>

    <select id="selectByUserId" resultMap="UserBalanceLogResultMap">
        SELECT * FROM user_balance_log 
        WHERE user_id = #{userId} AND is_deleted = 0
        ORDER BY create_time DESC
        LIMIT #{offset}, #{limit}
    </select>

    <select id="countByUserId" resultType="long">
        SELECT COUNT(*) FROM user_balance_log 
        WHERE user_id = #{userId} AND is_deleted = 0
    </select>

    <select id="selectByUserIdAndChangeType" resultMap="UserBalanceLogResultMap">
        SELECT * FROM user_balance_log 
        WHERE user_id = #{userId} AND change_type = #{changeType} AND is_deleted = 0
        ORDER BY create_time DESC
        LIMIT #{offset}, #{limit}
    </select>

    <select id="countByUserIdAndChangeType" resultType="long">
        SELECT COUNT(*) FROM user_balance_log 
        WHERE user_id = #{userId} AND change_type = #{changeType} AND is_deleted = 0
    </select>

    <select id="selectByUserIdAndTimeRange" resultMap="UserBalanceLogResultMap">
        SELECT * FROM user_balance_log 
        WHERE user_id = #{userId} 
          AND create_time BETWEEN #{startTime} AND #{endTime}
          AND is_deleted = 0
        ORDER BY create_time DESC
    </select>

</mapper> 