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

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

internal sealed class CreateServiceOptionValueCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateServiceOptionValueCommand, OperationResult<OptionValueDto>>
{
    public async ValueTask<OperationResult<OptionValueDto>> Handle(CreateServiceOptionValueCommand request, CancellationToken cancellationToken)
    {
        if (!await unitOfWork.CatalogRepository.GroupExistsAsync(request.OptionGroupId, cancellationToken))
            return OperationResult<OptionValueDto>.FailureResult(nameof(request.OptionGroupId), "Option group not found.");

        var value = new ServiceOptionValue
        {
            OptionGroupId = request.OptionGroupId,
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            SortOrder = request.SortOrder,
            IsActive = true
        };

        await unitOfWork.CatalogRepository.AddValueAsync(value, cancellationToken);
        await unitOfWork.CommitAsync();

        await CatalogCache.InvalidateAsync(cache, cancellationToken);

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