package com.huangzj.cross.cmd;

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.cmd.gen.CrossLinkRegisterCts;
import com.huangzj.cmd.gen.CrossLinkRegisterStc;
import com.huangzj.cmd.gen.PbService;
import com.huangzj.cmd.gen.Service4_Method;
import com.huangzj.cross.config.CrossLinkAcceptProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 区服 TCP 连上跨服后的注册握手（仅 {@link CommandSource#CROSS_TCP}）。
 */
@Component
@RequiredArgsConstructor
@Cmd(
        source = CommandSource.CROSS_TCP,
        serviceId = PbService.Service_4_VALUE,
        methodId = Service4_Method.Register_VALUE)
public class CrossLinkRegisterCommand extends AbstractTypedPbCommand<CrossLinkRegisterCts, CrossLinkRegisterStc.Builder> {

    private final CrossLinkAcceptProperties acceptProperties;

    @Override
    protected void run(CommandContext ctx, CrossLinkRegisterCts cts, CrossLinkRegisterStc.Builder stcBuilder) {
        String expected = acceptProperties.getExpectedToken();
        // 跨服未配置 expected-token 时不校验，方便本地多区服联调；生产环境建议两边配置一致
        if (StringUtils.hasText(expected) && !expected.equals(cts.getToken())) {
            stcBuilder.setOk(false).setMessage("token mismatch");
            return;
        }
        // server_id 用于日志、路由扩展；空则拒绝，避免匿名连接占坑
        if (!StringUtils.hasText(cts.getServerId())) {
            stcBuilder.setOk(false).setMessage("server_id required");
            return;
        }
        stcBuilder.setOk(true).setMessage("ok " + cts.getServerId());
    }
}
