package com.red.circle.other.adapter.app.activity;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.order.inner.model.enums.MonthlyRechargeType;
import com.red.circle.other.app.dto.cmd.SpinsTaskProgressUpdateCmd;
import com.red.circle.other.app.service.SpinsUserTaskProgressService;
import com.red.circle.other.app.util.DateTimeAsiaRiyadhUtils;
import com.red.circle.other.infra.database.rds.service.activity.UserActivityRechargeService;
import com.red.circle.other.inner.endpoint.activity.api.UserActivityRechargeClientApi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;

/**
 * 用户活动充值服务实现
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(UserActivityRechargeClientApi.API_PREFIX)
public class UserActivityRechargeClientController implements UserActivityRechargeClientApi {

    private final UserActivityRechargeService userActivityRechargeService;
    private final SpinsUserTaskProgressService spinsUserTaskProgressService;
    private final RedisService redisService;

    @Override
    public ResultResponse<Void> recordRecharge(Long userId, BigDecimal amount, String type) {
        userActivityRechargeService.recordRecharge(userId, amount, MonthlyRechargeType.valueOf(type));
        handleRechargeTask(userId, amount);
        return ResultResponse.success();
    }

    /**
     * 处理充值任务送券
     */
    private void handleRechargeTask(Long userId, BigDecimal amount) {
        try {
            BigDecimal totalAmount = incrementDailyRechargeAmount(userId, amount);
            
            log.info("Spins充值任务, userId={}, amount={}, totalAmount={}", userId, amount, totalAmount);

            // 转换为整数金额（美元）
            int progressValue = totalAmount.intValue();

            spinsUserTaskProgressService.updateTaskProgress(
                    new SpinsTaskProgressUpdateCmd()
                            .setUserId(userId)
                            .setTaskCode("SP_RECHARGE_1")
                            .setProgressValue(progressValue)
            );

            spinsUserTaskProgressService.updateTaskProgress(
                    new SpinsTaskProgressUpdateCmd()
                            .setUserId(userId)
                            .setTaskCode("SP_RECHARGE_10")
                            .setProgressValue(progressValue)
            );

            spinsUserTaskProgressService.updateTaskProgress(
                    new SpinsTaskProgressUpdateCmd()
                            .setUserId(userId)
                            .setTaskCode("SP_RECHARGE_50")
                            .setProgressValue(progressValue)
            );

            spinsUserTaskProgressService.updateTaskProgress(
                    new SpinsTaskProgressUpdateCmd()
                            .setUserId(userId)
                            .setTaskCode("SP_RECHARGE_100")
                            .setProgressValue(progressValue)
            );


            log.info("Spins充值任务处理成功, userId={}, totalAmount={}", userId, totalAmount);
        } catch (Exception e) {
            log.error("处理Spins充值任务失败, userId={}, amount={}", userId, amount, e);
        }
    }

    /**
     * 增加用户每日累计充值金额
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 当前累计充值金额
     */
    private BigDecimal incrementDailyRechargeAmount(Long userId, BigDecimal amount) {
        String redisKey = "spins:daily:recharge:amount:" + userId;

        // 转换为分（避免浮点数精度问题）
        long amountInCents = amount.multiply(new BigDecimal("100")).longValue();
        
        // 使用 Redis increment 原子操作
        Long totalCents = redisService.increment(redisKey, amountInCents);
        
        // 首次创建时设置过期时间
        if (totalCents.equals(amountInCents)) {
            long expireSeconds = DateTimeAsiaRiyadhUtils.getSecondsUntilMidnight();
            redisService.expire(redisKey, expireSeconds, TimeUnit.SECONDS);
        }
        
        // 转换回美元
        return new BigDecimal(totalCents).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
    }
}
