package com.njcn.gather.detection.controller;

import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.detection.lock.DetectionLock;
import com.njcn.gather.detection.lock.DetectionLockManager;
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import com.njcn.web.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 检测互斥锁管理接口。
 * - GET  /detection/lock/current      查询当前持锁状态；空闲返回 data=null
 * - POST /detection/lock/forceRelease 管理员强制释放
 *
 * 鉴权：默认由 AuthGlobalFilter 做 JWT 校验，登录用户均可访问；
 * 强释操作通过 @OperateInfo 落审计日志，谁操作谁担责。
 */
@Slf4j
@Api(tags = "检测互斥锁")
@RestController
@RequestMapping("/detection/lock")
@RequiredArgsConstructor
public class LockController extends BaseController {

    @GetMapping("/current")
    @ApiOperation("查询当前持锁状态；空闲返回 data=null")
    public HttpResult<DetectionLockHolderVO> current() {
        String methodDescribe = getMethodDescribe("current");
        DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
        DetectionLockHolderVO data = cur == null ? null : DetectionLockManager.toHolderVO(cur);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, data, methodDescribe);
    }

    @PostMapping("/forceRelease")
    @OperateInfo
    @ApiOperation("管理员强制释放检测锁")
    public HttpResult<?> forceRelease() {
        String methodDescribe = getMethodDescribe("forceRelease");
        String operator = RequestUtil.getUserId();
        DetectionLockManager.getInstance().forceRelease(operator, "ADMIN_FORCE");
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }
}
