using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.DeleteUserAddress;
public class DeleteUserAddressCommandHandler : IRequestHandler<DeleteUserAddressCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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