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

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

        var provinces = await cache.GetOrCreateAsync(
            GeoCache.ProvincesKey(version),
            async ct => await unitOfWork.GeoRepository.ListActiveProvincesAsync(ct),
            GeoCache.Ttl,
            cancellationToken);

        return OperationResult<IReadOnlyList<ProvinceDto>>.SuccessResult(provinces);
    }
}
