using Fantasy;
using Fantasy.Async;
using Fantasy.Network;
using Fantasy.Network.Interface;
using Fantasy.Platform.Net;
using NB.Game;

namespace NB.Gate;

public sealed class C2G_LoginRequestHandler : MessageRPC<C2G_LoginRequest, G2C_LoginResponse>
{
    protected override async FTask Run(Session session, C2G_LoginRequest request, G2C_LoginResponse response,
        Action reply)
    {
        if (string.IsNullOrEmpty(request.ToKen))
        {
            session.Dispose();
            return;
        }

        var scene = session.Scene;
        if (!GateJWTHelper.ValidateToken(scene, request.ToKen, out var accountId))
        {
            // 如果失败，表示肯定是恶意攻击、所以毫不犹疑，直接断开当前会话。
            session.Dispose();
            return;
        }

        // 在缓存中检查该账号是否存在
        var gateUnitManageComponent = scene.GetComponent<GateUnitManageComponent>();
        

        var gateUnit = gateUnitManageComponent.Online(session, accountId);

        if (gateUnit == null)
        {
            Log.Error("创建GateUnit失败");
            session.Dispose();
            return;
        }

        response.RoleId = gateUnit.AccountID;
        response.ErrorCode = await GateLoginHelper.Online(gateUnit);
        Log.Debug($"当前的Gate服务器:{session.Scene.SceneConfigId} accountId:{accountId}");
    }
}