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.Queries.GetCategoryOptionGroups;

internal sealed class GetCategoryOptionGroupsQueryHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<GetCategoryOptionGroupsQuery, OperationResult<IReadOnlyList<OptionGroupDto>>>
{
    public async ValueTask<OperationResult<IReadOnlyList<OptionGroupDto>>> Handle(GetCategoryOptionGroupsQuery request, CancellationToken cancellationToken)
    {
        var version = await CatalogCache.VersionAsync(cache, cancellationToken);

        var groups = await cache.GetOrCreateAsync(
            CatalogCache.OptionGroupsKey(version, request.CategoryId),
            async ct => await unitOfWork.CatalogRepository.GetApplicableGroupsAsync(request.CategoryId, ct),
            CatalogCache.Ttl,
            cancellationToken);

        return OperationResult<IReadOnlyList<OptionGroupDto>>.SuccessResult(groups);
    }
}
