package com.huimv.employment.controller.mcp;

import com.huimv.employment.common.web.R;
import com.huimv.employment.service.order.McpOrderService;
import com.huimv.employment.service.order.dto.McpOrderCloneRequest;
import com.huimv.employment.service.order.dto.McpOrderCloneResponse;
import com.huimv.employment.service.order.dto.McpOrderListResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * MCP 订单接口（交互规则 v2 §6.3.6、§6.3.7）。
 */
@RestController
@RequestMapping("/api/mcp/orders")
@Tag(name = "MCP-订单", description = "订单查询与克隆至草稿，需 X-Fe-Ai-Key + session_id")
public class McpOrderController {

    private final McpOrderService mcpOrderService;

    public McpOrderController(McpOrderService mcpOrderService) {
        this.mcpOrderService = mcpOrderService;
    }

    @GetMapping
    @Operation(summary = "统一订单查询",
            description = "按企业上下文查询历史/进行中订单，支持 status、limit 筛选，用于再来一单引导。",
            parameters = {
                    @Parameter(name = "session_id", in = ParameterIn.QUERY, required = true,
                            description = "会话标识，与 AI chat session_id / conversation_no 一致"),
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER,
                            description = "内网服务密钥"),
                    @Parameter(name = "status", in = ParameterIn.QUERY,
                            description = "订单状态筛选，如 completed、confirmed、in_progress"),
                    @Parameter(name = "limit", in = ParameterIn.QUERY,
                            description = "返回条数，默认 10，最大 50")
            })
    public R<McpOrderListResponse> listOrders(
            @RequestParam("session_id") String sessionId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Integer limit) {
        return R.ok(mcpOrderService.listOrders(sessionId, status, limit));
    }

    @PostMapping("/clone")
    @Operation(summary = "克隆历史订单至草稿",
            description = "将历史订单快照转化为新草稿并绑定当前会话，随后可 GET /api/mcp/draft/info 检查待补字段。",
            parameters = {
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER)
            })
    public R<McpOrderCloneResponse> cloneToDraft(@Validated @RequestBody McpOrderCloneRequest request) {
        return R.ok(mcpOrderService.cloneToDraft(request.getSessionId(), request));
    }
}
