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

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

        var districts = await cache.GetOrCreateAsync(
            GeoCache.DistrictsKey(version, request.CityId),
            async ct => await unitOfWork.GeoRepository.ListActiveDistrictsAsync(request.CityId, ct),
            GeoCache.Ttl,
            cancellationToken);

        return OperationResult<IReadOnlyList<DistrictDto>>.SuccessResult(districts);
    }
}
