using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserContractCQ.Commands.UpdateUserContract;
public class UpdateUserContractCommandHandler : IRequestHandler<UpdateUserContractCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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