package com.bizzan.bitrade.controller;

import com.bizzan.bitrade.engine.ContractCoinMatch;
import com.bizzan.bitrade.engine.ContractCoinMatchFactory;
import com.bizzan.bitrade.entity.*;
import com.bizzan.bitrade.service.MemberContractPositionService;
import com.bizzan.bitrade.service.RedisLock;
import com.bizzan.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 管理后台专用强平接口，绕过用户会话，直接调用撮合引擎。
 * 仅供同 Eureka 集群内的 admin 服务通过 Ribbon 调用。
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminCloseController {

    @Autowired
    private MemberContractPositionService memberContractPositionService;

    @Autowired
    private ContractCoinMatchFactory contractCoinMatchFactory;

    @Autowired
    private RedisLock redisLock;

    /**
     * 强平指定仓位（市价全平）。
     * 与 /swap/order/close-all 逻辑相同，去掉用户会话校验。
     */
    @PostMapping("force-close-position")
    public MessageResult forceClosePosition(@RequestParam Long positionId) {
        MemberContractPosition position = memberContractPositionService.findOne(positionId);
        if (position == null) {
            return MessageResult.error(404, "仓位不存在");
        }
        if (position.getStatus() == ContractPositionStatus.DONE) {
            return MessageResult.error(400, "仓位已平仓");
        }

        ContractCoin contractCoin = position.getCoin();
        if (contractCoin == null) {
            return MessageResult.error(400, "合约币种不存在");
        }

        ContractCoinMatch match = contractCoinMatchFactory.getContractCoinMatch(contractCoin.getSymbol());
        if (match == null) {
            log.error("[AdminClose] 撮合引擎未找到 symbol={}", contractCoin.getSymbol());
            return MessageResult.error(500, "撮合引擎未运行");
        }

        // 跟单仓位需要锁定跟单账户，与 /close-all 一致
        boolean isFollow = position.getFollowPositionId() != null;
        if (isFollow && !redisLock.lockFollowAccount(position.getMemberId())) {
            return MessageResult.error(429, "账户操作中，请稍后重试");
        }

        position.setCloseType(CloseType.ADMIN_CLOSE);

        try {
            match.dealAllCloseOrder(position);
            log.info("[AdminClose] 强平成功 positionId={} memberId={} symbol={} isFollow={}",
                    positionId, position.getMemberId(), contractCoin.getSymbol(), isFollow);
        } catch (Exception e) {
            log.error("[AdminClose] 强平异常 positionId={}", positionId, e);
            return MessageResult.error(500, "强平失败: " + e.getMessage());
        } finally {
            if (isFollow) redisLock.unlockFollowAccount(position.getMemberId());
        }

        return MessageResult.success("操作成功");
    }
}
