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

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

internal sealed class SetDistrictActiveCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<SetDistrictActiveCommand, OperationResult<bool>>
{
    public async ValueTask<OperationResult<bool>> Handle(SetDistrictActiveCommand request, CancellationToken cancellationToken)
    {
        var district = await unitOfWork.GeoRepository.GetDistrictAsync(request.Id, cancellationToken);
        if (district is null)
            return OperationResult<bool>.NotFoundResult("District not found.");

        district.IsActive = request.IsActive;

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

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