namespace Netina.Repository.Handlers.Products;

public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, ProductLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;

    public CreateProductCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }

    public async Task<ProductLDto> Handle(CreateProductCommand request, CancellationToken cancellationToken)
    {

        var ent = 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);

        foreach (var specification in request.Specifications)
        {
            ent.AddSpecification(specification.Title, specification.Detail, specification.Value,
                specification.IsFeature, specification.ParentId);
        }

        foreach (var file in request.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }

        

        _repositoryWrapper.SetRepository<Product>().Add(ent);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        if (request.IsSpecialOffer)
        {
            var discount = request.SpecialOffer.Adapt<DiscountLDto>();
            discount.ProductId = ent.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 ent.AdaptToLDto();
    }
}