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

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

        district.NameFa = request.NameFa;
        district.NameEn = request.NameEn;
        district.SortOrder = request.SortOrder;

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

        return OperationResult<DistrictDto>.SuccessResult(
            new DistrictDto(district.Id, district.CityId, district.NameFa, district.NameEn, district.SortOrder));
    }
}
