using Fantasy;
using Fantasy.Async;
using Fantasy.Network.Interface;

namespace NB.Chat;

public class C2S_DeleteMailRequestHandler : RouteRPC<SocialUnit, C2S_DeleteMailRequest, S2C_DeleteMailResponse>
{
    protected override async FTask Run(SocialUnit entity, C2S_DeleteMailRequest request,
        S2C_DeleteMailResponse response, Action reply)
    {
        if (request.Id < 1)
        {
            response.ErrorCode = ErrorCode.ErrArgs;
            return;
        }

        var mailManageComponent = entity.Scene.GetComponent<MailManageComponent>();
        if (mailManageComponent == null)
        {
            Log.Error("组件不存在 MailManageComponent");
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var conversation = await mailManageComponent.GetConversation(entity.Id, request.Id);
        if (conversation == null)
        {
            response.ErrorCode = ErrorCode.ErrArgs;
            return;
        }

        conversation.RemoveId.Add(entity.Id);
        if (conversation.RemoveId.Count > 1)
        {
            //都删除了，则吧会话直接移除掉
            await mailManageComponent.DeleteConversation(entity.Id, request.Id);
        }
        else
        {
            await conversation.Save();
        }
    }
}