package tech.easyflow.admin.controller.ai;

import com.easyagents.mcp.client.McpEnvironmentCheckResult;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.transaction.annotation.Transactional;
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;
import tech.easyflow.ai.entity.Mcp;
import tech.easyflow.ai.service.AgentResourceReferenceService;
import tech.easyflow.ai.service.McpService;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.controller.BaseCurdController;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.common.web.jsonbody.JsonBody;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigInteger;

/**
 *  控制层。
 *
 * @author wangGangQiang
 * @since 2026-01-04
 */
@RestController
@RequestMapping("/api/v1/mcp")
public class McpController extends BaseCurdController<McpService, Mcp> {
    public McpController(McpService service) {
        super(service);
    }

    /**
     * 获取 MCP 列表关键字搜索字段。
     *
     * @return 标题和描述属性
     */
    @Override
    protected String[] getKeywordSearchProperties() {
        return new String[]{"title", "description"};
    }

    @Resource
    private AgentResourceReferenceService agentResourceReferenceService;
    @Override
    public Result<?> save(Mcp entity) {
        return service.saveMcp(entity);
    }

    @Override
    public Result<?> update(Mcp entity) {
        return service.updateMcp(entity);
    }

    /**
     * 删除未被 Agent 绑定的 MCP。
     *
     * @param id MCP ID
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> remove(Serializable id) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        if (account == null || account.getTenantId() == null) {
            throw new BusinessException("当前登录状态失效，请重新登录后再试");
        }
        // 锁定 MCP 资源行，与 Agent 绑定校验串行，避免检查后并发写入绑定。
        Mcp mcp = service.getOne(QueryWrapper.create()
                .eq(Mcp::getId, id)
                .eq(Mcp::getTenantId, account.getTenantId())
                .forUpdate());
        if (mcp == null) {
            throw new BusinessException("MCP 不存在或无权删除");
        }
        agentResourceReferenceService.assertMcpUnused(new BigInteger(String.valueOf(id)));
        service.removeMcp(id);
        return Result.ok();
    }

    @Override
    public Result<Page<Mcp>> page(HttpServletRequest request, String sortKey, String sortType, Long pageNumber, Long pageSize) {
        Result<Page<Mcp>> page = super.page(request, sortKey, sortType, pageNumber, pageSize);
        return service.pageMcp(page);
    }

    @PostMapping("/getMcpTools")
    public Result<Mcp> getMcpTools(@JsonBody("id") String id) {

        return Result.ok(service.getMcpTools(id));
    }

    @PostMapping("/check")
    public Result<McpEnvironmentCheckResult> check(@JsonBody("configJson") String configJson) {
        return Result.ok(service.checkMcp(configJson));
    }


    @GetMapping("pageTools")
    public Result<Page<Mcp>> pageTools(HttpServletRequest request, String sortKey, String sortType, Long pageNumber, Long pageSize) {
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1L;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10L;
        }

        QueryWrapper queryWrapper = buildQueryWrapper(request);
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));
        Page<Mcp> mcpPage = queryPage(new Page<>(pageNumber, pageSize), queryWrapper);

        return Result.ok(service.pageTools(mcpPage));
    }
}
