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

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

        province.NameFa = request.NameFa;
        province.NameEn = request.NameEn;
        province.SortOrder = request.SortOrder;

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

        return OperationResult<ProvinceDto>.SuccessResult(
            new ProvinceDto(province.Id, province.NameFa, province.NameEn, province.SortOrder));
    }
}
