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

namespace Baya.Application.Features.Geography.Queries.GetGeoTree;

internal sealed class GetGeoTreeQueryHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<GetGeoTreeQuery, OperationResult<IReadOnlyList<ProvinceTreeDto>>>
{
    public async ValueTask<OperationResult<IReadOnlyList<ProvinceTreeDto>>> Handle(GetGeoTreeQuery request, CancellationToken cancellationToken)
    {
        var version = await GeoCache.VersionAsync(cache, cancellationToken);

        var tree = await cache.GetOrCreateAsync(
            GeoCache.TreeKey(version),
            async ct => await unitOfWork.GeoRepository.GetActiveTreeAsync(ct),
            GeoCache.Ttl,
            cancellationToken);

        return OperationResult<IReadOnlyList<ProvinceTreeDto>>.SuccessResult(tree);
    }
}
