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 EndOfAnnVisitorToMenuNotificationHandler : NewRockBaseHandler, INotificationHandler<EndOfAnnVisitorToMenuNotification>
    {
        private readonly ICallRepository _callRepository;
        private readonly ICallDetailRepository _callDetailRepository;
        private readonly IIvrDomainService _ivrDomainService;

        public EndOfAnnVisitorToMenuNotificationHandler(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(EndOfAnnVisitorToMenuNotification notification, CancellationToken cancellationToken)
        {
            var model = await _callRepository.GetAsync(
                x => x.ConversationId == notification.Visitor.Id && x.FromNo == notification.Visitor.From &&
                     x.ToNo == notification.Visitor.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.Visitor.CallId,
                    ConversationId = notification.Visitor.Id,
                    EventName = notification.Attribute,
                    FromNo = notification.Visitor.From,
                    ToNo = notification.Visitor.To
                };
                await _callDetailRepository.AddAsync(detail, cancellationToken);

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

                await HandlerIvr(runModel, model, cancellationToken);
            }


        }
    }
}
