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.UpdateServiceOptionValue;

internal sealed class UpdateServiceOptionValueCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<UpdateServiceOptionValueCommand, OperationResult<OptionValueDto>>
{
    public async ValueTask<OperationResult<OptionValueDto>> Handle(UpdateServiceOptionValueCommand request, CancellationToken cancellationToken)
    {
        var value = await unitOfWork.CatalogRepository.GetValueAsync(request.Id, cancellationToken);
        if (value is null)
            return OperationResult<OptionValueDto>.NotFoundResult("Option value not found.");

        value.NameFa = request.NameFa;
        value.NameEn = request.NameEn;
        value.SortOrder = request.SortOrder;
        value.IsActive = request.IsActive;

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

        return OperationResult<OptionValueDto>.SuccessResult(new OptionValueDto(
            value.Id, value.NameFa, value.NameEn, value.SortOrder, value.IsActive));
    }
}
