using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.TagCQ.Commands.UpdateTag;
public class UpdateTagCommandHandler : IRequestHandler<UpdateTagCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(UpdateTagCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Tags
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(Tag), request.Id);
        request.Adapt(entity);
        _context.Tags.Update(entity);
        entity.AddDomainEvent(new UpdateTagEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}

