using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.UpdateUserAddress;
public class UpdateUserAddressCommandHandler : IRequestHandler<UpdateUserAddressCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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