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

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

internal sealed class SetProvinceActiveCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<SetProvinceActiveCommand, OperationResult<bool>>
{
    public async ValueTask<OperationResult<bool>> Handle(SetProvinceActiveCommand request, CancellationToken cancellationToken)
    {
        var province = await unitOfWork.GeoRepository.GetProvinceAsync(request.Id, cancellationToken);
        if (province is null)
            return OperationResult<bool>.NotFoundResult("Province not found.");

        province.IsActive = request.IsActive;

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

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