using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using XF.Domain.Repository;

namespace Hotline.CallCenter.Calls
{
    /// <summary>
    /// 生成CallId与CallNo形成映射并持久化
    /// </summary>
    public class CallIdManager
    {
        private readonly IRepository<CallidRelation> _callorderRepository;
        private readonly ILogger<CallIdManager> _logger;

        public CallIdManager(
            IRepository<CallidRelation> callorderRepository,
            ILogger<CallIdManager> logger)
        {
            _callorderRepository = callorderRepository;
            _logger = logger;
        }

        public async Task<string> GetOrSetAsync(string callNo, CancellationToken cancellationToken)
        {
            var callOrder = await _callorderRepository.GetAsync(callNo, cancellationToken);
            if (callOrder == null)
            {
                callOrder = new CallidRelation
                {
                    Id = callNo,
                    CallId = Ulid.NewUlid().ToString(),
                };
                try
                {
                    await _callorderRepository.AddAsync(callOrder, cancellationToken);
                }
                catch (Exception e)
                {
                    _logger.LogError($"写入callidRelation失败：{e.Message}");
                }
            }
            return callOrder.CallId;
        }
    }
}
