using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using DocumentFormat.OpenXml.Office2010.Excel;
//using System.ComponentModel.DataAnnotations;
namespace pavesys_iRAP.Business
{
    public static class AuthModule
    {
        public static string accessToken = string.Empty;
        public static bool isAdmin = false; // Mantém se o usuário logado atual é admin ou não
        public static bool hasViaSegura = false;
        //public static int loggedUserId = 0;


        public static async Task<(bool,int,bool)> TryLogin(string username, string password)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "auth/login";

            var loginData = new
            {
                username = username,
                password = password
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);

                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(loginData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Login successful. Response:");
                        Debug.WriteLine(responseBody);
                        var authResponse = JsonConvert.DeserializeAnonymousType(responseBody, new { token = "", role = "" ,viaSegura = ""});


                        accessToken = authResponse.token;
                        isAdmin = authResponse.role switch
                        {
                            "ADMIN" => true,
                            _ => false
                        };
                        bool viaSeguraEnabled = authResponse.viaSegura switch {
                            "DENIED" => false,
                            _ => true
                        };
                        hasViaSegura = viaSeguraEnabled;
                        return (true,0,viaSeguraEnabled);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        int statusError = (int)response.StatusCode;
                        Debug.WriteLine(statusError);
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return (false, statusError,false);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return (false,999,false);
            }
        }

        public static async Task<ObservableCollection<IRapUser>> GetIRapUsersAsync()
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "admin/list";

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await client.GetAsync(endpoint);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("GET /admin/list successful. Response:");
                        Debug.WriteLine(responseBody);
                        var usersList = JsonConvert.DeserializeObject<ObservableCollection<IRapUser>>(responseBody);
                        return usersList!;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return new ObservableCollection<IRapUser>();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return new ObservableCollection<IRapUser>();

            }
        }
        public static async Task<(bool,string)> CreateUser(string _username, string _role, string _email, string _password, string _empresa, string _datExpiracao)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "admin/register";

            var newUserData = new
            {
                username = _username,
                role = _role,
                email = _email,
                password = _password,
                empresa = _empresa,
                datExpiracao = _datExpiracao,
                viaSegura = 0
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(newUserData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        //Debug.WriteLine("Created user successufully Response:");
                        //Debug.WriteLine(responseBody);
                        return (true, responseBody);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return (false, errorContent);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return (false, ex.Message);
            }
        }

        public static async Task<bool> CheckUserSession()
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "auth/session-check";

            var userToken = new
            {
                token = accessToken
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(userToken);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;   
            }
        }


        public static async Task<bool> CheckRecoverToken(string _token)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "/auth/validateResetPasswordToken";

            var userToken = new
            {
                token = _token
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(userToken);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public static async Task<bool> CheckAndChangePassword(string _token, string _password) 
        {
            if (!await CheckRecoverToken(_token))
                return false;
            if(!await ChangePassword(_token, _password))
                return false;

            return true;
        }
        public static async Task<bool> ChangePassword(string _token, string _password) 
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "/auth/changePasswordByToken";

            var userToken = new
            {
                token = _token,
                password = _password
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(userToken);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public static async Task<bool> ResetPassEmail(string _email)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "/auth/resetPassword";

            var userToken = new
            {
                email = _email
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(userToken);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public static async Task<bool> LogOut()
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "auth/logout";

            var token = new
            {
                token = accessToken,
                
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(token);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return true;
            }
        }

        public static async Task<bool> DeleteUser(int userId)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = $"admin/delete/{userId}";

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await client.DeleteAsync(endpoint);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("GET /admin/list successful. Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Erro ao deletar usuário");
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;

            }
        }
        public static async Task ChangeRole(int _userId,string _role) 
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "admin/changeUserRole";

            var newRoleData  = new
            {
                id= _userId,
                role = _role,
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    string jsonContent = JsonConvert.SerializeObject(newRoleData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
            }
        }
        public static async Task ChangeViaSegura(int _userId, int _accessType)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "admin/changeUserViaSeguraAccess";

            var newRoleData = new
            {
                id = _userId,
                viaSegura = _accessType,
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    string jsonContent = JsonConvert.SerializeObject(newRoleData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
            }
        }


        public static async Task ChangePassword(int _userId, string _password) 
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "admin/changeUserPassword";

            var newPasswordData = new
            {
                id = _userId,
                password = _password,
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);


                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(newPasswordData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send Put request
                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Created user successufully Response:");
                        Debug.WriteLine(responseBody);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
            }
        }



        public static async Task<bool> ActivateUser(int userId)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = $"admin/activate/{userId}";
            StringContent content = new StringContent("", Encoding.UTF8, "application/json");

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await client.PutAsync(endpoint,content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("PUT activate successful. Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Erro ao deletar usuário");
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;

            }
        }

        public static async Task<bool> SuspendUser(int userId)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = $"admin/suspend/{userId}";
            StringContent content = new StringContent("", Encoding.UTF8, "application/json");

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("PUT susped successful. Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Erro ao deletar usuário");
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;

            }
        }

        public static async Task<bool> ExtendExpiration(int userId,string newDate)
        {
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = $"/admin/renewExpiration/{userId}";
            var newExpireDate = new
            {
                expDate = newDate
            };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(newExpireDate);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send Put request
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await client.PutAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("PUT susped successful. Response:");
                        Debug.WriteLine(responseBody);
                        return true;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Erro ao deletar usuário");
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
                return false;

            }
        }

    }
}
