using NetinaShop.Domain.Entities.ProductCategories;

namespace NetinaShop.Repository.Handlers.ProductCategories;

public class CreateProductCategoryCommandHandler : IRequestHandler<CreateProductCategoryCommand,ProductCategoryLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

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

    public async Task<ProductCategoryLDto> Handle(CreateProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var ent = ProductCategory.Create(request.Name, request.Description, request.IsMain);
        if (request.ParentId != default)
            ent.SetParent(request.ParentId);
        foreach (var file in request.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        _repositoryWrapper.SetRepository<ProductCategory>().Add(ent);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return ent.AdaptToLDto();
    }
}