using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserRoleCQ.Commands.CreateNewUserRole;
public class CreateNewUserRoleCommandHandler : IRequestHandler<CreateNewUserRoleCommand, CreateNewUserRoleResponseDto>
{
    private readonly IApplicationDbContext _context;

    public CreateNewUserRoleCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<CreateNewUserRoleResponseDto> Handle(CreateNewUserRoleCommand request,
        CancellationToken cancellationToken)
    {
        var entity = request.Adapt<UserRole>();
        await _context.UserRoles.AddAsync(entity, cancellationToken);
        entity.AddDomainEvent(new CreateNewUserRoleEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return entity.Adapt<CreateNewUserRoleResponseDto>();
    }
}
