using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Geography;
using Baya.Domain.Entities.Geography;
using Mediator;

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

internal sealed class CreateDistrictCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateDistrictCommand, OperationResult<DistrictDto>>
{
    public async ValueTask<OperationResult<DistrictDto>> Handle(CreateDistrictCommand request, CancellationToken cancellationToken)
    {
        var city = await unitOfWork.GeoRepository.GetCityAsync(request.CityId, cancellationToken);
        if (city is null)
            return OperationResult<DistrictDto>.FailureResult(nameof(request.CityId), "City not found.");

        var district = new District
        {
            CityId = request.CityId,
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            SortOrder = request.SortOrder,
            IsActive = true
        };

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

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