using Newtonsoft.Json.Linq;

namespace ESuite.UI.E2E.Helpers.Mail
{
    public class Mailer
    {

        public static string CustomizeUserEmail(string email, string customText)
        {
            string[] parts = email.Split('@');
            if (parts.Length == 2)
            {
                string firstPart = parts[0];
                string domainPart = parts[1];
                firstPart += $".{customText}";
                string modifiedEmail = $"{firstPart}@{domainPart}";

                return modifiedEmail;
            }
            else
            {
                throw new Exception($"Email '{email}' should have one sign '@'!");
            }
        }

        public static async Task<string> GetIdFromPapercutAsync()
        {
            try
            {
                string apiUrl = "http://localhost:37408/api/messages?limit=1";

                using HttpClient client = new();
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(content) ?? throw new Exception("Deserialized JSON is null");
                    string id = json!.Messages[0].Id;

                    return id;
                }
                else
                {
                    throw new Exception($"Response is: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }
        private static string GetLinkFromBodyMessage(string text, string? startSymbols = "http", string? endSymbols = "\"")
        {
            int startIndex = text.IndexOf(startSymbols!);
            int endIndex = text.IndexOf(endSymbols!, startIndex);

            if (startIndex != -1 && endIndex != -1)
            {
                string url = text[startIndex..endIndex];

                return url;
            }
            else
            {
                throw new Exception($"I can't find the link");
            }
        }

        public static async Task<string> GetLinkFromHtmlBodyViaPapercut(string id, string? LinkText = "")
        {
            try
            {
                string apiUrl = $"http://localhost:37408/api/messages/{id}";

                using HttpClient client = new();
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(content))
                    {
                        dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(content) ?? throw new Exception("Deserialized JSON is null");
                        string htmlBody = json!.HtmlBody;
                        return GetLinkFromBodyMessage(htmlBody);

                    }
                    else
                    {
                        throw new Exception("Received empty or null content.");
                    }
                }
                else
                {
                    throw new Exception($"Response status is: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }

        public static async Task<string> GetLinkFromHtmlBodyViaTestMailApp(string clientEmail, string apiKey, string nameSpace, int retryCount = 0)
        {
            if (string.IsNullOrEmpty(apiKey))
            {
                throw new Exception("API key is empty! Check release variables!");
            }

            try
            {
                string apiUrl = $"https://api.testmail.app/api/json?apikey={apiKey}&namespace={nameSpace}";

                using HttpClient client = new();
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(content))
                    {
                        dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(content) ?? throw new Exception("Deserialized JSON is null");

                        try
                        {
                            if (json.emails != null && !string.IsNullOrEmpty(json.emails[0].html.ToString()))
                            {

                                JArray emails = (JArray)json["emails"];

                                foreach (JObject email in emails.Cast<JObject>())
                                {
                                    JObject toParsed = (JObject)email["to_parsed"]![0]!;
                                    string address = (string)toParsed["address"]!;

                                    if (address == clientEmail)
                                    {
                                        return GetLinkFromBodyMessage((string)email["html"]!);
                                    }
                                    else
                                    {
                                        throw new Exception($"I can't find the email with the recipient: {clientEmail}");
                                    }
                                }
                                throw new Exception("I can't find address in email");
                            }
                            else
                            {
                                throw new Exception("Empty emails");
                            }
                        }
                        catch (Exception)
                        {
                            if (retryCount < 3)
                            {
                                await Task.Delay(TimeSpan.FromMinutes(1));

                                return await GetLinkFromHtmlBodyViaTestMailApp(clientEmail, apiKey, nameSpace, retryCount + 1);
                            }
                            else
                            {
                                throw new Exception("Exceeded maximum retry limit to get Email.");
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Received empty or null content.");
                    }
                }
                else
                {
                    throw new Exception($"Response status is: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }

    }
}
