namespace Netina.Repository.Handlers.Products;

public class UpdateProductCommandHandler(IRepositoryWrapper repositoryWrapper,IMartenRepositoryWrapper martenRepositoryWrapper, IMediator mediator,ICurrentUserService currentUserService)
    : IRequestHandler<UpdateProductCommand, bool>
{
    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);
        if (currentUserService.UserId == null)
            throw new BaseApiException(ApiResultStatusCode.UnAuthorized, "User id is wrong");
        if(!Guid.TryParse(currentUserService.UserId,out Guid userId))
            throw new BaseApiException(ApiResultStatusCode.UnAuthorized, "User id is wrong");
        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,
            userId);
        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);
            }
        }
        else
        {
            var discount = await repositoryWrapper.SetRepository<ProductDiscount>()
                .TableNoTracking
                .FirstOrDefaultAsync(d => d.ProductId == newEnt.Id && d.IsSpecialOffer, cancellationToken);
            if (discount != null)
                await mediator.Send(new DeleteDiscountCommand(discount.Id), cancellationToken);
        }

        await UpdateFaqAsync(newEnt, request.Faqs, cancellationToken);

        return true;
    }


    private async Task UpdateFaqAsync(Product newEnt, Dictionary<string, string> faqs, CancellationToken cancellationToken)
    {
        var url = newEnt.GetWebSiteUrl();
        var oldFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == newEnt.Slug, cancellationToken);
        var newFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == url, cancellationToken);
        if (oldFaq != null)
            await mediator.Send(new DeleteFaqCommand(oldFaq.Id), cancellationToken);

        if (newFaq == null)
            await mediator.Send(new CreateFaqCommand(faqs, url, newEnt.EnglishName), cancellationToken);
        else
            await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.EnglishName), cancellationToken);
    }
}