using Castle.DynamicProxy;
using IRaCIS.Application.Services;
using IRaCIS.Application.Contracts;
using Microsoft.Extensions.Logging;
using IRaCIS.Core.Infrastructure.Extention;

namespace IRaCIS.Core.API.Utility.AOP
{
    /// <summary>
    ///服务动态生成api  AOP 此时会失效
    /// </summary>
    public class UserAddAOP : IInterceptor
    {
        private readonly IMailVerificationService _mailVerificationService;
        private readonly ILogger<UserAddAOP> _logger;

        public UserAddAOP(IMailVerificationService mailVerificationService, ILogger<UserAddAOP> logger)
        {
            _mailVerificationService = mailVerificationService;
            _logger = logger;
        }
        public void Intercept(IInvocation invocation)
        {

            var userInfo = (invocation.Arguments[0] as UserCommand).IfNullThrowConvertException();


            //处理拦截的方法
            invocation.Proceed();

            //在此 发送邮件
            dynamic result = invocation.ReturnValue;

            if (result.IsSuccess)
            {
                var userId = result.Data.Id;
                var verificationCode = result.Data.VerificationCode;


                _logger.LogInformation($"Sent to {userInfo.UserName} email {userInfo.EMail} init password {verificationCode}");

                _mailVerificationService.SendMail(userId, userInfo.UserName, userInfo.EMail, verificationCode).GetAwaiter().GetResult();

            }



        }
    }
}