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

internal sealed class CreateCityCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateCityCommand, OperationResult<CityDto>>
{
    public async ValueTask<OperationResult<CityDto>> Handle(CreateCityCommand request, CancellationToken cancellationToken)
    {
        if (!await unitOfWork.GeoRepository.ProvinceExistsAsync(request.ProvinceId, cancellationToken))
            return OperationResult<CityDto>.FailureResult(nameof(request.ProvinceId), "Province not found.");

        var city = new City
        {
            ProvinceId = request.ProvinceId,
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            SortOrder = request.SortOrder,
            IsActive = true
        };

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

        return OperationResult<CityDto>.SuccessResult(
            new CityDto(city.Id, city.ProvinceId, city.NameFa, city.NameEn, city.SortOrder));
    }
}
