using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.FactorDetailsCQ.Commands.UpdateFactorDetails;
public class UpdateFactorDetailsCommandHandler : IRequestHandler<UpdateFactorDetailsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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