package com.table.transfer.module.controller;


import com.rabbitmq.client.Channel;
import com.table.transfer.config.RabbitConfig;
import com.table.transfer.module.enpty.TransferRecord;
import com.table.transfer.module.enpty.TransferRequest;
import com.table.transfer.module.enpty.TransferResponse;
import com.table.transfer.module.service.EthereumService;
import com.table.transfer.module.service.TransferRecordService;
import com.table.transfer.module.service.TronService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;


@Slf4j
@Validated
@Component
public class TransferController {

    @Resource
    TronService tronService;
    @Resource
    EthereumService ethereumService;
    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    TransferRecordService transferRecordService;

    @RabbitListener(queues = RabbitConfig.TRANSFER_REQUEST_QUEUE, ackMode = "MANUAL")
    public void transfer (@RequestBody TransferRequest request, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        TransferResponse response = new TransferResponse();
        try {
            log.info("收到转账请求: chain={}, to={}, amount={}", request.getChain(), request.getToAddress(), request.getAmount());
            String chain = request.getChain().toUpperCase();
            if (chain.equals("TRON")){
                response= tronService.transfer(request);
            }
            if (chain.equals("ETH")||chain.equals("BSC")){
                response= ethereumService.transfer(request);
            }

            if (response.isSuccess()) {
                log.info("转账成功: txHash={}", response.getTransactionHash());
            } else {
                log.error("转账失败: error={}", response.getMessage());
            }
        } catch (Exception e) {
            response = TransferResponse.error(e.getMessage());
            log.error("转账处理异常: {}", e.getMessage(), e);
        } finally {
            response.setRequestId(request.getRequestId());
            try {
                TransferRecord record = TransferRecord.create(request, response);
                transferRecordService.save(record);
            }catch (Exception e){
                log.error("什么?写入转账记录失败了?{}", e.getMessage(), e);
            }

            //回调发送结果
            rabbitTemplate.convertAndSend(
                    RabbitConfig.TRANSFER_EXCHANGE,
                    RabbitConfig.TRANSFER_RESULT,
                    response
            );
            channel.basicAck(deliveryTag, false); // 总是 ACK，绝不 requeue,避免重复转账
        }
    }
}