package com.yaoai.domain.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yaoai.domain.entity.TenantBalance;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface TenantBalanceMapper extends BaseMapper<TenantBalance> {

    @Select("SELECT * FROM tenant_balances WHERE tenant_id = #{tenantId}")
    TenantBalance findByTenantId(Long tenantId);

    /** 乐观锁扣减：balance -= amount, total_spent += amount, version++ */
    @Update("UPDATE tenant_balances SET balance = balance - #{amount}, total_spent = total_spent + #{amount}, version = version + 1 WHERE tenant_id = #{tenantId} AND balance >= #{amount}")
    int tryDeduct(@Param("tenantId") Long tenantId, @Param("amount") java.math.BigDecimal amount);

    /** 充值：balance += amount, total_recharged += amount */
    @Update("UPDATE tenant_balances SET balance = balance + #{amount}, total_recharged = total_recharged + #{amount} WHERE tenant_id = #{tenantId}")
    int recharge(@Param("tenantId") Long tenantId, @Param("amount") java.math.BigDecimal amount);
}
