using Microsoft.EntityFrameworkCore;

namespace Netina.Repository.Handlers.Addresses;

public class DeleteAddressCommandHandler : IRequestHandler<DeleteAddressCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteAddressCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteAddressCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<UserAddress>()
            .TableNoTracking
            .FirstOrDefaultAsync(u => u.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Address not found", ApiResultStatusCode.NotFound);
        _repositoryWrapper.SetRepository<UserAddress>()
            .Delete(ent);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}