using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Configs;
using Hotline.CallCenter.Ivrs;
using Hotline.DI;
using Hotline.Realtimes;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Notifications.NewRockCallCenter;
using MediatR;
using Microsoft.Extensions.Options;
using NewRock.Sdk;

namespace Hotline.Application.Handlers.CallCenter.FlowControl
{
    [Injection(EventHandlerType = EEventHandlerType.CallCenter, Label = AppDefaults.CallCenterType.XunShi)]
    public class EndOfAnnOuterToMenuNotificationHandler : NewRockBaseHandler, INotificationHandler<EndOfAnnOuterToMenuNotification>
    {
        private readonly ICallRepository _callRepository;
        private readonly ICallDetailRepository _callDetailRepository;
        private readonly IIvrDomainService _ivrDomainService;
        public EndOfAnnOuterToMenuNotificationHandler(ICallRepository callRepository, ICallDetailRepository callDetailRepository, IIvrDomainService ivrDomainService, INewRockClient newRockClient, IOptionsSnapshot<CallCenterConfiguration> callcenterOptions, ICallCacheManager callCacheManager, IRealtimeService realtimeService) : base(newRockClient, callcenterOptions, callRepository, callCacheManager, realtimeService)
        {
            _callRepository = callRepository;
            _callDetailRepository = callDetailRepository;
            _ivrDomainService = ivrDomainService;
        }

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

                var runModel = await _ivrDomainService.GetVoiceEndAnswerAsync(notification.MenuId, cancellationToken);

                await HandlerIvr(runModel, model, cancellationToken);
            }
        }
    }
}
