namespace NetinaShop.Repository.Handlers.Products;

public class UpdateProductCommandHandler : IRequestHandler<UpdateProductCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

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

        var newEnt = Product.Create(request.PersianName, request.EnglishName, request.Summery, request.ExpertCheck,
            request.Tags, 
            request.Warranty,
            request.BeDisplayed,
            request.Cost,
            request.PackingCost,
            ent.ReviewCount,
            ent.Rate,
            ent.Viewed,
            request.BrandId,
            request.CategoryId);
        newEnt.Id = ent.Id;

        var dbSpecifications = await _repositoryWrapper.SetRepository<Specification>().TableNoTracking
            .Where(s => s.ProductId == ent.Id).ToListAsync(cancellationToken);
        foreach (var dbSpecification in dbSpecifications)
        {
            if (request.Specifications.Any(s => s.Id == dbSpecification.Id))
            {
                _repositoryWrapper.SetRepository<Specification>().Delete(dbSpecification);
                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }

        foreach (var specification in request.Specifications.Where(s => s.Id == default))
        {
            newEnt.AddSpecification(specification.Title, specification.Detail, specification.Value, specification.IsFeature, specification.ParentId);
        }



        var dbFiles = await _repositoryWrapper.SetRepository<ProductStorageFile>().TableNoTracking
            .Where(s => s.ProductId == ent.Id).ToListAsync(cancellationToken);
        foreach (var dbFile in dbFiles)
        {
            if (request.Files.Any(s => s.Id == dbFile.Id))
            {
                _repositoryWrapper.SetRepository<ProductStorageFile>().Delete(dbFile);
                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }
        foreach (var file in request.Files.Where(f=>f.Id==default))
        {
            newEnt.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        _repositoryWrapper.SetRepository<Product>().Update(newEnt);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}