namespace NetinaShop.Repository.Handlers.Products;

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

    public CreateProductCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }

    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,0,0,0,
            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);
        return ent.AdaptToLDto();
    }
}