using NetinaCMS.Repository.Repositories.Base.Contracts;

namespace NetinaCMS.Repository.Handlers.BlogCategories;

public class UpdateBlogCategoryCommandHandler : IRequestHandler<UpdateBlogCategoryCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public UpdateBlogCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(UpdateBlogCategoryCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<BlogCategory>()
            .TableNoTracking
            .FirstOrDefaultAsync(bc => bc.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Blog Category not found", ApiResultStatusCode.NotFound);

        var newEnt = BlogCategory.Create(request.Name, request.Description);
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;
        newEnt.Id = ent.Id;

        _repositoryWrapper.SetRepository<BlogCategory>()
            .Update(newEnt);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;    
    }
}