package com.huangzj.server.cmd.cmds;

import com.huangzj.base.cmd.AbstractTypedPbCommand;
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.cmd.gen.CmdRpcEnvelope;
import com.huangzj.cmd.gen.CrossForwardCts;
import com.huangzj.cmd.gen.CrossForwardStc;
import com.huangzj.cmd.gen.CrossProxyCts;
import com.huangzj.cmd.gen.CrossProxyStc;
import com.huangzj.cmd.gen.PbService;
import com.huangzj.cmd.gen.Service2_Method;
import org.springframework.stereotype.Component;

/**
 * 路径2：客户端 → 区服 → 跨服处理 → 回到区服再加工 → 回客户端。
 * 跨服侧为 {@link PbService#Service_2} + {@link Service2_Method#Method2}。
 */
@Component
@Cmd(
        source = CommandSource.Client_TCP,
        serviceId = PbService.Service_2_VALUE,
        methodId = Service2_Method.Method2_VALUE)
public class TcpPath2CrossThenServerCommand extends AbstractTypedPbCommand<CrossProxyCts, CrossProxyStc.Builder> {

    @Override
    protected void run(CommandContext ctx, CrossProxyCts cts, CrossProxyStc.Builder stcBuilder) throws Exception {
        CrossRpcInvoker inv = ctx.crossRpc();
        if (inv == null) {
            throw new IllegalStateException("cross unavailable");
        }
        // 客户端协议是 CrossProxy*；跨服只认 CrossForward*，这里在区服内做一次「外壳→内壳」转换
        CrossForwardCts forward = CrossForwardCts.newBuilder().setTrace(cts.getTrace()).build();
        CmdRpcEnvelope toCross = CmdRpcEnvelope.newBuilder()
                .setServiceId(PbService.Service_2_VALUE)
                .setMethodId(Service2_Method.Method2_VALUE)
                .setPayload(forward.toByteString())
                .build();
        // CrossTcpClient 会为该CmdRpcEnvelope写入 link_seq 并同步等跨服回包
        CmdRpcEnvelope back = inv.roundTrip(toCross);
        CrossForwardStc cfs = CrossForwardStc.parseFrom(back.getPayload());
        // 把跨服结果写回客户端协议的 STC，并追加区服侧字段证明二次处理过
        stcBuilder
                .setTrace(cfs.getTrace())
                .setCrossTimeMs(cfs.getCrossTimeMs())
                .setServerNote("path2: server after cross @" + System.currentTimeMillis());
    }
}
