Refactor and optimize this C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Net.Sockets;
using DnsClient;
using EmailSoftWare.Models.Extensions.Enums;

namespace EmailSoftWare.Models.Managers
{
    public class DomainSettings
    {
        public string Domain { get; set; }
        public string? ImapHostname { get; set; }
        public int? ImapPort { get; set; }
        public string? PopHostname { get; set; }
        public int? PopPort { get; set; }
    }

    internal class DomainManager
    {
        private static readonly HttpService HttpService = new HttpService();
        private bool _isFound = false;
        public async Task<DomainSettings> SearchSettingsAsync(string domain)
        {
            bool UseMXRecords = UserConfigManager.UserConfig.DomainSettingsSearch_MX;
            bool UseSRVRecords = UserConfigManager.UserConfig.DomainSettingsSearch_SRV;
            bool UseWebConfigs = UserConfigManager.UserConfig.DomainSettingsSearch_Web;
            bool UseSubdomains = UserConfigManager.UserConfig.DomainSettingsSearch_Selection;

            if (UseWebConfigs)
            {
                var result = await SearchHostnameByAutoConfig(domain);
                if (_isFound)
                {
                    return result;
                }

                result = await SearchHostnameByThunderBird(domain);
                if (_isFound)
                {
                    return result;
                }

                result = await SearchHostnameByFireTrust(domain);
                if (_isFound)
                {
                    return result;
                }
            }

            if (UseMXRecords)
            {
                var result = GetMailServerInfoByMX(domain);
                if (_isFound)
                {
                    return result;
                }
            }

            return null;

            //if (UseSRVRecords)
            //{
            //    settingsFound = GetMailServerInfoBySRV(domain);
            //    if (_isFound) return;
            //}

            //if (UseSubdomains)
            //{
            //    settingsFound = CheckPorts(domain);
            //    if (_isFound) return;
            //}
        }

        private DomainSettings GetMailServerInfoByMX(string domain)
        {
            try
            {
                var lookup = new LookupClient();
                var result = lookup.Query(domain, QueryType.MX);
                var mxRecords = result.Answers.MxRecords().OrderBy(mx => mx.Preference).ToList();

                foreach (var mxRecord in mxRecords)
                {
                    string mailServer = mxRecord.Exchange.Value.TrimEnd('.');

                    if (mailServer.Contains("google."))
                    {
                        var domainSettings = new DomainSettings()
                        {
                            Domain = domain,
                            ImapHostname = "imap.gmail.com",
                            ImapPort = 993,
                            PopHostname = null,
                            PopPort = null
                        };

                        _isFound = true;

                        return domainSettings;
                    }
                    else if (mailServer.Contains("outlook.") || mailServer.Contains("office365."))
                    {
                        var domainSettings = new DomainSettings()
                        {
                            Domain = domain,
                            ImapHostname = "outlook.office365.com",
                            ImapPort = 993,
                            PopHostname = null,
                            PopPort = null
                        };

                        _isFound = true;

                        return domainSettings;
                    }
                    else if (mailServer.Contains("yahoo."))
                    {
                        var domainSettings = new DomainSettings()
                        {
                            Domain = domain,
                            ImapHostname = "imap.mail.yahoo.com",
                            ImapPort = 993,
                            PopHostname = null,
                            PopPort = null
                        };

                        _isFound = true;

                        return domainSettings;
                    }
                    else if (mailServer.Contains("aol."))
                    {
                        var domainSettings = new DomainSettings()
                        {
                            Domain = domain,
                            ImapHostname = "imap.aol.com",
                            ImapPort = 993,
                            PopHostname = null,
                            PopPort = null
                        };

                        _isFound = true;

                        return domainSettings;
                    }
                    else if (mailServer.Contains("icloud.") || mailServer.Contains("me.com"))
                    {
                        var domainSettings = new DomainSettings()
                        {
                            Domain = domain,
                            ImapHostname = "imap.mail.me.com",
                            ImapPort = 993,
                            PopHostname = null,
                            PopPort = null
                        };

                        _isFound = true;

                        return domainSettings;
                    }
                    //else if (mailServer.Contains("zoho"))
                    //{
                    //    Console.WriteLine("Detected Zoho Mail. Use Zoho's IMAP/SMTP settings.");
                    //    // imap.zoho.com (SSL, порт 993)
                    //    break;
                    //}
                    //else if (mailServer.Contains("gmx"))
                    //{
                    //    Console.WriteLine("Detected GMX. Use GMX's IMAP/SMTP settings.");
                    //    // imap.gmx.com (SSL/TLS, порт 993)
                    //    break;
                    //}
                    //else if (mailServer.Contains("fastmail"))
                    //{
                    //    Console.WriteLine("Detected FastMail. Use FastMail's IMAP/SMTP settings.");
                    //    // imap.fastmail.com (SSL/TLS, порт 993)
                    //    break;
                    //}
                    //else if (CheckPort(mailServer, 993, "IMAP (SSL/TLS)") ||
                    //         CheckPort(mailServer, 995, "POP3 (SSL/TLS)") ||
                    //         CheckPort(mailServer, 143, "IMAP (STARTTLS)") ||
                    //         CheckPort(mailServer, 110, "POP3 (STARTTLS)"))
                    //{
                    //    break;
                    //}
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        static bool CheckPort(string hostname, int port, string protocol)
        {
            try
            {
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.ReceiveTimeout = 3000;
                    tcpClient.SendTimeout = 3000;
                    tcpClient.Connect(hostname, port);
                    if (tcpClient.Connected)
                    {
                        Console.WriteLine($"{protocol} is available on port {port}");
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{protocol} is not available on port {port}: {ex.Message}");
            }

            return false;
        }

        private async Task<DomainSettings> SearchHostnameByAutoConfig(string domain)
        {
            try
            {
                var url = "http://autoconfig." + domain + "/mail/config-v1.1.xml?emailaddress=info@" + domain;
                using var client = new HttpClient { Timeout = TimeSpan.FromMilliseconds(2500) };
                var xmlString = await client.GetStringAsync(url);
                var xdoc = XDocument.Parse(xmlString);

                var imapServer = xdoc.Descendants("incomingServer").FirstOrDefault(e => (string)e.Attribute("type") == "imap");
                var imapHost = imapServer?.Element("hostname")?.Value;
                var imapPort = imapServer?.Element("port")?.Value;

                var pop3Server = xdoc.Descendants("incomingServer").FirstOrDefault(e => (string)e.Attribute("type") == "pop3");
                var pop3Host = pop3Server?.Element("hostname")?.Value;
                var pop3Port = pop3Server?.Element("port")?.Value;

                if (imapHost != null || pop3Host != null)
                {
                    var domainSettings = new DomainSettings()
                    {
                        Domain = domain,
                        ImapHostname = imapHost,
                        ImapPort = int.TryParse(imapPort, out var imapResult) ? imapResult : (int?)null,
                        PopHostname = pop3Host,
                        PopPort = int.TryParse(pop3Port, out var popResult) ? popResult : (int?)null
                    };

                    _isFound = true;

                    return domainSettings;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        private async Task<DomainSettings> SearchHostnameByThunderBird(string domain)
        {
            try
            {
                var url = "https://autoconfig.thunderbird.net/v1.1/" + domain;
                var xmlString = await HttpService.GetStringAsync(url);
                var xdoc = XDocument.Parse(xmlString);

                var imapServer = xdoc.Descendants("incomingServer").FirstOrDefault(e => (string)e.Attribute("type") == "imap");
                var imapHost = imapServer?.Element("hostname")?.Value;
                var imapPort = imapServer?.Element("port")?.Value;

                var pop3Server = xdoc.Descendants("incomingServer").FirstOrDefault(e => (string)e.Attribute("type") == "pop3");
                var pop3Host = pop3Server?.Element("hostname").Value;
                var pop3Port = pop3Server?.Element("port").Value;

                if (imapHost != null || pop3Host != null)
                {
                    var domainSettings = new DomainSettings()
                    {
                        Domain = domain,
                        ImapHostname = imapHost,
                        ImapPort = int.TryParse(imapPort, out var imapResult) ? imapResult : (int?)null,
                        PopHostname = pop3Host,
                        PopPort = int.TryParse(pop3Port, out var popResult) ? popResult : (int?)null
                    };

                    _isFound = true;

                    return domainSettings;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        private async Task<DomainSettings> SearchHostnameByFireTrust(string domain)
        {
            try
            {
                var url = "https://emailsettings.firetrust.com/settings?q=" + domain;
                var jsonString = await HttpService.GetStringAsync(url);

                var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
                var emailSettings = JsonSerializer.Deserialize<EmailSettings>(jsonString, options);

                var imapSetting = Array.Find(emailSettings.Settings, setting => setting.Protocol == "IMAP");
                var popSetting = Array.Find(emailSettings.Settings, setting => setting.Protocol == "POP3");

                if (imapSetting?.Address != null || popSetting?.Address != null)
                {
                    var domainSettings = new DomainSettings()
                    {
                        Domain = domain,
                        ImapHostname = imapSetting?.Address,
                        ImapPort = imapSetting?.Port ?? null,
                        PopHostname = popSetting?.Address,
                        PopPort = popSetting?.Port ?? null
                    };

                    _isFound = true;

                    return domainSettings;
                }

                return null;
            }
            catch
            {
                return null;
            }
        }
    }

    public class HttpService
    {
        private readonly HttpClient _httpClient;

        public HttpService()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(2500) };
        }

        public async Task<string> GetStringAsync(string url)
        {
            return await _httpClient.GetStringAsync(url);
        }
    }

    public class EmailSettings
    {
        [JsonPropertyName("settings")]
        public Setting[] Settings { get; set; }
    }

    public class Setting
    {
        [JsonPropertyName("protocol")]
        public string Protocol { get; set; }

        [JsonPropertyName("address")]
        public string Address { get; set; }

        [JsonPropertyName("port")]
        public int Port { get; set; }
    }
}