using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Catalog;
using Baya.Application.Models.Common;
using Mediator;

namespace Baya.Application.Features.Catalog.Commands.UpdateServiceCategory;

internal sealed class UpdateServiceCategoryCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<UpdateServiceCategoryCommand, OperationResult<ServiceCategoryDto>>
{
    public async ValueTask<OperationResult<ServiceCategoryDto>> Handle(UpdateServiceCategoryCommand request, CancellationToken cancellationToken)
    {
        var category = await unitOfWork.CatalogRepository.GetCategoryAsync(request.Id, cancellationToken);
        if (category is null)
            return OperationResult<ServiceCategoryDto>.NotFoundResult("Category not found.");

        category.NameFa = request.NameFa;
        category.NameEn = request.NameEn;
        category.DescriptionFa = request.DescriptionFa;
        category.DescriptionEn = request.DescriptionEn;
        category.IconKey = request.IconKey;
        category.SortOrder = request.SortOrder;

        await unitOfWork.CommitAsync();
        await CatalogCache.InvalidateAsync(cache, cancellationToken);

        return OperationResult<ServiceCategoryDto>.SuccessResult(new ServiceCategoryDto(
            category.Id, category.NameFa, category.NameEn, category.DescriptionFa, category.DescriptionEn,
            category.IconKey, category.SortOrder, category.IsActive));
    }
}
