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

internal sealed class CreateProvinceCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateProvinceCommand, OperationResult<ProvinceDto>>
{
    public async ValueTask<OperationResult<ProvinceDto>> Handle(CreateProvinceCommand request, CancellationToken cancellationToken)
    {
        var province = new Province
        {
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            SortOrder = request.SortOrder,
            IsActive = true
        };

        await unitOfWork.GeoRepository.AddProvinceAsync(province, cancellationToken);
        await unitOfWork.CommitAsync();

        await GeoCache.InvalidateAsync(cache, cancellationToken);

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