// Licensed to Timothy Schenk under the GNU AGPL Version 3 License.

using Continuity.AuthServer.DB;
using Microsoft.EntityFrameworkCore;
using Rai.PacketMediator;
using Wonderking.Packets.Incoming;
using Wonderking.Packets.Outgoing;

namespace Continuity.AuthServer.PacketHandlers;

public class CharacterNameCheckHandler : IPacketHandler<CharacterNameCheckPacket, AuthSession>
{
    private readonly WonderkingContext _wonderkingContext;

    public CharacterNameCheckHandler(WonderkingContext wonderkingContext)
    {
        _wonderkingContext = wonderkingContext;
    }

    public async Task HandleAsync(CharacterNameCheckPacket packet, AuthSession session,
        CancellationToken cancellationToken)
    {
        var isTaken =
            await _wonderkingContext.Characters.AnyAsync(c => c.Name == packet.Name,
                cancellationToken);
        var responsePacket = new CharacterNameCheckPacketResponse { IsTaken = isTaken };

        await session.SendAsync(responsePacket);
    }
}