using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.DI;
using Hotline.Realtimes;
using Hotline.Share.Dtos.Realtime;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Notifications.NewRockCallCenter;
using MediatR;

namespace Hotline.Application.Handlers.CallCenter.FlowControl
{
    [Injection(EventHandlerType = EEventHandlerType.CallCenter, Label = AppDefaults.CallCenterType.XunShi)]
    public class AnsweredExtToOuterToExtNotificationHandler : INotificationHandler<AnsweredExtToOuterToExtNotification>
    {
        private readonly ICallRepository _callRepository;
        private readonly ICallDetailRepository _callDetailRepository;

        public AnsweredExtToOuterToExtNotificationHandler(ICallRepository callRepository, ICallDetailRepository callDetailRepository)
        {
            _callRepository = callRepository;
            _callDetailRepository = callDetailRepository;
        }

        public async Task Handle(AnsweredExtToOuterToExtNotification notification, CancellationToken cancellationToken)
        {
            var model = await _callRepository.GetAsync(x =>
                x.ConversationId == notification.Outer.Id && x.ToNo == notification.Outer.To &&
                x.Trunk == notification.Outer.Trunk && x.CreationTime >= DateTime.Now.AddHours(-2), true, x => x.CreationTime, cancellationToken);
            if (model != null)
            {
                model.CallStatus = ECallStatus.Answered;
                model.AnsweredTime = DateTime.Now;
                await _callRepository.UpdateAsync(model, cancellationToken);
                var detail = new CallDetail()
                {
                    CallId = model.Id,
                    CallStatus = ECallStatus.Answered,
                    ConversationId = notification.Outer.Id,
                    OMCallId = notification.Outer.CallId,
                    EventName = notification.Attribute,
                    AnswerNo = notification.Outer.To,
                    FromNo = notification.Outer.From,
                    ToNo = notification.Outer.To,
                };
                await _callDetailRepository.AddAsync(detail, cancellationToken);
            }
        }
    }
}
