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

namespace Baya.Application.Features.Geography.Commands.SetCityActive;

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

        city.IsActive = request.IsActive;

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

        return OperationResult<bool>.SuccessResult(true);
    }
}
