package org.dromara.system.mapper;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dromara.system.domain.AiUserBalance;
import org.dromara.system.domain.vo.AiBalanceOverviewVo;
import org.dromara.system.domain.vo.AiDailyStatVo;
import org.dromara.system.domain.vo.AiUserBalanceVo;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户AI账户余额Mapper接口
 *
 * @author mearo
 * @date 2026-07-01
 */
@InterceptorIgnore(tenantLine = "true")
public interface AiUserBalanceMapper extends BaseMapperPlus<AiUserBalance, AiUserBalanceVo> {

    @Select("select * from ai_user_balance where tenant_id = #{tenantId} limit 1")
    AiUserBalance selectByTenantId(@Param("tenantId") String tenantId);

    /**
     * 扣减余额（带防透支条件）
     * 返回 0 表示余额不足或租户不存在
     */
// 原第32行：[BUG-3] 注释写“带防透支条件”，实际 SQL 没有 balance >= amount 条件
    @Update("UPDATE ai_user_balance " +
        "SET balance = balance - #{amount}, " +
        "    total_consume = total_consume + #{amount}, " +
        "    update_time = now() " +
        "WHERE tenant_id = #{tenantId} ")
    int decrBalance(@Param("tenantId") String tenantId, @Param("amount") Long amount);


    /**
     * 增加余额（退款）
     * 只加 balance，不动 total_consume
     */
    @Update("UPDATE ai_user_balance " +
        "SET balance = balance + #{amount}, " +
        "    total_consume = total_consume - #{amount}, " +
        "    update_time = now() " +
        "WHERE tenant_id = #{tenantId}")
    int incrBalance(@Param("tenantId") String tenantId, @Param("amount") Long amount);


    @Update("update ai_user_balance set warn_threshold = #{warnThreshold}, video_task_max = #{videoTaskMax}, update_time = now() " +
        "where tenant_id = #{tenantId}")
// 原第54行：[BUG-7] 仅提供更新字段的接口，任何地方都没有读取/校验该上限
    int updateThreshold(@Param("tenantId") String tenantId, @Param("warnThreshold") Long warnThreshold, @Param("videoTaskMax") Integer videoTaskMax);


    @InterceptorIgnore(tenantLine = "true")
    AiBalanceOverviewVo getOverview(@Param("tenantId") String tenantId);

}
