using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.Products;

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

    public UpdateProductCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }
    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,
            request.HasExpressDelivery,
            request.Stock,
            request.MaxOrderCount,
            request.BrandId,
            request.CategoryId);
        newEnt.Id = ent.Id;
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;

        var dbSpecifications = await _repositoryWrapper.SetRepository<Specification>().TableNoTracking
            .Where(s => s.ProductId == ent.Id).ToListAsync(cancellationToken);
        foreach (var dbSpecification in dbSpecifications)
        {
            if (request.Specifications.FirstOrDefault(s => s.Id != dbSpecification.Id) == null)
            {
                _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.FirstOrDefault(s => s.Id == dbFile.Id)==null)
            {
                _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);

        if (request.IsSpecialOffer)
        {
            var discount = request.SpecialOffer.Adapt<DiscountLDto>();
            discount.ProductId = newEnt.Id;
            discount.IsSpecialOffer = true;
            discount.Type = DiscountType.Product;
            discount.HasCode = false;
            discount.IsInfinity = true;
            if (request.SpecialOffer.Id == default)
            {
                var discountRequest = discount.Adapt<CreateDiscountCommand>();
                await _mediator.Send(discountRequest, cancellationToken);
            }
            else
            {
                var discountRequest = discount.Adapt<UpdateDiscountCommand>();
                await _mediator.Send(discountRequest, cancellationToken);
            }
        }

        return true;
    }
}