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.Commands.UpdateCity;

internal sealed class UpdateCityCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<UpdateCityCommand, OperationResult<CityDto>>
{
    public async ValueTask<OperationResult<CityDto>> Handle(UpdateCityCommand request, CancellationToken cancellationToken)
    {
        var city = await unitOfWork.GeoRepository.GetCityAsync(request.Id, cancellationToken);
        if (city is null)
            return OperationResult<CityDto>.NotFoundResult("City not found.");

        city.NameFa = request.NameFa;
        city.NameEn = request.NameEn;
        city.SortOrder = request.SortOrder;

        await unitOfWork.CommitAsync();
        await GeoCache.InvalidateAsync(cache, cancellationToken);

        return OperationResult<CityDto>.SuccessResult(
            new CityDto(city.Id, city.ProvinceId, city.NameFa, city.NameEn, city.SortOrder));
    }
}
