#nullable enable
namespace Hims.Infrastructure.Helpers
{
    using System;
    using System.Threading.Tasks;
    using Domain.Configurations;
    using Domain.Helpers;
    using RestSharp;
    using Shared.EntityModels;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;


    /// <inheritdoc />
    public class SMSHelper : ISMSHelper
    {
        /// <summary>
        /// The application configuration.
        /// </summary>
        private readonly IApplicationConfiguration applicationConfiguration;

        /// <summary>
        /// Initializes a new instance of the <see cref="SMSHelper"/> class.
        /// </summary>
        /// <param name="applicationConfiguration">
        /// The application Configuration.
        /// </param>
        public SMSHelper(IApplicationConfiguration applicationConfiguration)
        {
            this.applicationConfiguration = applicationConfiguration;
        }

        /// <inheritdoc />
        public async Task<IRestResponse?> SendSMSAsync(string mobile, string body, CountryModel countryModel)
        {
            if (string.IsNullOrEmpty(countryModel.SMSUrl))
            {
                return null!;
            }

            mobile = !string.IsNullOrEmpty(this.applicationConfiguration.DefaultMobile) ? this.applicationConfiguration.DefaultMobile : mobile;
            countryModel.CountryCode = "+" + countryModel.CountryCode;
            if (countryModel.CountryCode.Contains("91"))
            {
                var client = new RestClient(countryModel.SMSUrl);

                var request = new RestRequest(Method.POST);
                request.AddHeader("Content-Type", "application/json");
                request.AddQueryParameter("workingkey", countryModel.SMSAuthorization);
                request.AddQueryParameter("to", countryModel.CountryCode + mobile);
                request.AddQueryParameter("sender", countryModel.SMSFrom);
                request.AddQueryParameter("message", body);

                return await client.ExecuteAsync(request);
            }
            else
            {
                var client = new RestClient(countryModel.SMSUrl.Replace("@Username", countryModel.SMSUsername));
                var requestBody = @"{""from"":""" + countryModel.SMSFrom + @""", ""to"":[""" + countryModel.CountryCode + mobile + @"""], ""body"":""" + body + @"""}";
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", countryModel.SMSAuthorization);
                request.AddHeader("Content-Type", "application/json");
                request.AddParameter("application/json", requestBody, ParameterType.RequestBody);

                return await client.ExecuteAsync(request);
            }
        }

        /// <inheritdoc />
        public async Task<Tuple<IRestResponse, string>> SendLabReportSMSAsync(string mobile, string body, CountryModel countryModel, string url)
        {
            if (string.IsNullOrEmpty(countryModel.SMSUrl))
            {
                return new Tuple<IRestResponse, string>(null, null);
            }

            var tinyURLBody = new TinyUrlBody
            {
                URL = url,
                Domain = "tiny.one",
                Alias = string.Empty,
                Tags = string.Empty
            };

            var tinyUrl = new RestClient(this.applicationConfiguration.TinyUrlLink);
            var tinyUrlRequest = new RestRequest(Method.POST);
            tinyUrlRequest.AddQueryParameter("api_token", this.applicationConfiguration.TinyUrlAuthToken);
            tinyUrlRequest.AddHeader("Content-Type", "application/json");
            tinyUrlRequest.AddHeader("Accept", "application/json");
            var test = JsonConvert.SerializeObject(tinyURLBody, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
            tinyUrlRequest.AddJsonBody(test);

            var shortUrlRequest = await tinyUrl.ExecuteAsync<object>(tinyUrlRequest);
            var shortURl = string.Empty;
            if (shortUrlRequest.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var testObj = JsonConvert.DeserializeObject<TinyURLResponseMainBody>(shortUrlRequest.Content);
                shortURl += (testObj != null && testObj.Data != null && !string.IsNullOrEmpty(testObj.Data.tiny_url)) ? testObj.Data.tiny_url : url;
            }

            body += shortURl;
            body += $@" to view. - CareAxes";

#pragma warning disable CS8604 // Possible null reference argument.
            return new Tuple<IRestResponse, string>(await SendSMSAsync(mobile, body, countryModel), shortURl);
#pragma warning restore CS8604 // Possible null reference argument.
        }

        public Task<Tuple<IRestResponse, string>> SendPdfLinkSMSAsync(string patientMobile, string messageBody, CountryModel countryModel, string createPdfLink)
        {
            throw new NotImplementedException();
        }
    }
}

