package com.bizzan.bitrade.controller;

import com.bizzan.bitrade.entity.AirdropRecord;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.service.AirdropPoolService;
import com.bizzan.bitrade.util.MessageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import static com.bizzan.bitrade.constant.SysConstant.SESSION_MEMBER;

/**
 * 用户空投领取接口，仅限有质押的用户领取
 *
 * @author auto
 * @date 2026-05-17
 */
@Api(value = "AirdropController", tags = "用户空投接口")
@RestController
@RequestMapping("/airdrop")
@Slf4j
public class AirdropController {

    @Autowired
    private AirdropPoolService airdropPoolService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 查询当前用户是否具备领取空投的资格（有活跃质押 + 邀请下级 ≥ 3 人）
     *
     * @param member 当前登录用户
     * @return 资格校验结果，data 为 true 表示有资格，false 表示无资格
     */
    @ApiOperation(value = "查询空投领取资格", notes = "校验用户是否满足领取空投条件：持有活跃质押且已邀请至少3名下级")
    @PostMapping("/eligibility")
    public MessageResult checkEligibility(@SessionAttribute(SESSION_MEMBER) AuthMember member) {
        return airdropPoolService.checkEligibility(member.getId());
    }

    /**
     * 领取名下所有待领取的空投奖励，直接到账资金账户
     *
     * @param member 当前登录用户
     * @return 操作结果（含到账总金额）
     */
    @ApiOperation(value = "领取空投", notes = "满足条件（活跃质押+邀请≥3人）的用户一键领取名下全部待领取空投，同步记录流水")
    @PostMapping("/claim")
    public MessageResult claim(@SessionAttribute(SESSION_MEMBER) AuthMember member) {
        MessageResult result = airdropPoolService.claim(member.getId());
        // 事务提交后发送 MQ 通知，避免消费方读到事务未提交的旧数据
        if (result.getCode() == 0) {
            kafkaTemplate.send("trading-account-change", member.getId() + "");
        }
        return result;
    }

    /**
     * 分页查询当前用户的历史空投领取记录
     *
     * @param member   当前登录用户
     * @param pageNo   页码（从1开始）
     * @param pageSize 每页条数
     * @return 领取记录分页数据
     */
    @ApiOperation(value = "查询我的空投记录", notes = "分页查询当前用户历史空投领取记录")
    @PostMapping("/records")
    public MessageResult getMyRecords(@SessionAttribute(SESSION_MEMBER) AuthMember member,
                                      @RequestParam(defaultValue = "1") int pageNo,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        Page<AirdropRecord> page = airdropPoolService.getUserAirdropRecords(member.getId(), pageNo, pageSize);
        return MessageResult.success("success", page);
    }
}
