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

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

        var cities = await cache.GetOrCreateAsync(
            GeoCache.CitiesKey(version, request.ProvinceId),
            async ct => await unitOfWork.GeoRepository.ListActiveCitiesAsync(request.ProvinceId, ct),
            GeoCache.Ttl,
            cancellationToken);

        return OperationResult<IReadOnlyList<CityDto>>.SuccessResult(cities);
    }
}
