using Microsoft.EntityFrameworkCore;

namespace Netina.Repository.Handlers.Products;

public class ChangeProductDisplayedCommandHandler : IRequestHandler<ChangeProductDisplayedCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public ChangeProductDisplayedCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(ChangeProductDisplayedCommand 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,
            request.BeDisplayed, ent.Cost, ent.PackingCost, ent.HasExpressDelivery, ent.Stock, ent.MaxOrderCount,
            ent.BrandId,
            ent.CategoryId);
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;
        newEnt.Id = ent.Id;

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

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