using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Warehouses;

namespace Netina.Repository.Handlers.Warehouses;

public class UpdateShippingCommandHandler : IRequestHandler<UpdateShippingCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public UpdateShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(UpdateShippingCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<Shipping>().TableNoTracking
            .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Shipping not found", ApiResultStatusCode.NotFound);

        var newEnt = Shipping.Create(request.Name, request.WarehouseName, request.IsExpressShipping, request.IsShipBySeller,
            request.IsOriginalWarehouse,request.DeliveryCost,request.WorkingDays);
        newEnt.Id = ent.Id;
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;
        _repositoryWrapper.SetRepository<Shipping>().Update(newEnt);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}