package com.huangzj.server.cmd.cmds;

import com.huangzj.base.cmd.Cmd;
import com.huangzj.base.cmd.CommandContext;
import com.huangzj.base.cmd.CommandSource;
import com.huangzj.base.cmd.CrossRpcInvoker;
import com.huangzj.base.cmd.GameCommand;
import com.huangzj.cmd.gen.CmdRpcEnvelope;
import com.huangzj.cmd.gen.PbService;
import com.huangzj.cmd.gen.Service2_Method;
import com.huangzj.cmd.gen.Service3_Method;
import org.springframework.stereotype.Component;

/**
 * 路径3：客户端 → 区服 → 跨服处理 → 回到区服只做透明中转。
 * 请求体须与跨服 {@link PbService#Service_2} + {@link Service2_Method#Method2} 的 CTS 一致。
 */
@Component
@Cmd(
        source = CommandSource.Client_TCP,
        serviceId = PbService.Service_3_VALUE,
        methodId = Service3_Method.Method3_VALUE)
public class TcpPath3CrossRelayCommand implements GameCommand {

    @Override
    public CmdRpcEnvelope execute(CommandContext ctx, CmdRpcEnvelope request) throws Exception {
        CrossRpcInvoker inv = ctx.crossRpc();
        if (inv == null) {
            throw new IllegalStateException("cross unavailable");
        }
        // 路径3：客户端 payload 已是跨服 CTS 形态，区服只改CmdRpcEnvelope上的 service/method 指向跨服接口
        CmdRpcEnvelope toCross = CmdRpcEnvelope.newBuilder()
                .setServiceId(PbService.Service_2_VALUE)
                .setMethodId(Service2_Method.Method2_VALUE)
                .setPayload(request.getPayload())
                .build();
        CmdRpcEnvelope back = inv.roundTrip(toCross);
        // 对客户端仍表现为 Service_3/Method3；link_seq 沿用入站请求，跨服侧 seq 由 CrossTcpClient 单独维护
        return CmdRpcEnvelope.newBuilder()
                .setServiceId(request.getServiceId())
                .setMethodId(request.getMethodId())
                .setCrossRet(request.getCrossRet())
                .setLinkSeq(request.getLinkSeq())
                .setPayload(back.getPayload())
                .build();
    }
}
