using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;

namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;

public class UpdateBlogCategoryCommandHandler : IRequestHandler<UpdateBlogCategoryCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public UpdateBlogCategoryCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(UpdateBlogCategoryCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.BlogCategories.FindAsync(new object[] { request.Id }, cancellationToken);
        if (entity == null || entity.IsDeleted)
            throw new NotFoundException(nameof(BlogCategory), request.Id);

        entity.Title = request.Title;
        entity.Slug = request.Slug.ToLower();
        entity.Description = request.Description;
        entity.IconName = request.IconName;
        entity.SortOrder = request.SortOrder;
        entity.IsActive = request.IsActive;

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
