namespace Netina.Repository.Handlers.Products;

public class ChangeProductCostCommandHandler(IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<ChangeProductCostCommand, bool>
{
    public async Task<bool> Handle(ChangeProductCostCommand request, CancellationToken cancellationToken)
    {

        var ent = await repositoryWrapper.SetRepository<Product>()
            .TableNoTracking
            .FirstOrDefaultAsync(p => p.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Product not found");
        var newEnt = Product.Create(ent.PersianName, ent.EnglishName, ent.Summery, ent.ExpertCheck, ent.Tags,
            ent.Warranty,
            ent.BeDisplayed, request.Cost, ent.PackingCost, ent.HasExpressDelivery, ent.Stock, ent.MaxOrderCount,
            ent.BrandId,
            ent.CategoryId,
            ent.AuthorId);
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;
        newEnt.Id = ent.Id;

        repositoryWrapper.SetRepository<Product>()
            .Update(newEnt);

        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}