package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.Distributor;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;

@Mapper
public interface DistributorMapper extends BaseMapper<Distributor> {

    @Select("SELECT MAX(code) FROM t_distributor WHERE deleted = 0")
    String selectMaxCode();

    @Select("SELECT COUNT(*) FROM t_distributor WHERE phone = #{phone} AND deleted = 0 AND id != #{excludeId}")
    int countByPhone(@Param("phone") String phone, @Param("excludeId") Long excludeId);

    @Update("UPDATE t_distributor SET total_referrals = total_referrals + 1, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int incrementTotalReferrals(@Param("id") Long id);

    @Update("UPDATE t_distributor SET valid_referrals = valid_referrals + 1, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int incrementValidReferrals(@Param("id") Long id);

    @Update("UPDATE t_distributor SET commission_balance = commission_balance + #{amount}, total_commission = total_commission + #{amount}, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int addCommissionBalance(@Param("id") Long id, @Param("amount") BigDecimal amount);

    @Update("UPDATE t_distributor SET commission_balance = commission_balance - #{amount}, frozen_amount = frozen_amount + #{amount}, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int freezeAmount(@Param("id") Long id, @Param("amount") BigDecimal amount);

    @Update("UPDATE t_distributor SET frozen_amount = frozen_amount - #{amount}, total_withdrawn = total_withdrawn + #{amount}, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int deductWithdrawal(@Param("id") Long id, @Param("amount") BigDecimal amount);

    @Update("UPDATE t_distributor SET commission_balance = commission_balance + #{amount}, frozen_amount = frozen_amount - #{amount}, update_time = NOW() WHERE id = #{id} AND deleted = 0")
    int unfreezeAmount(@Param("id") Long id, @Param("amount") BigDecimal amount);
}
