using System;
using System.Collections.Generic;
using System.Data;
using Npgsql;

namespace ComputerShopWpf.Services
{
    public class AuthService
    {
        public bool Login(string login, string password, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                errorMessage = "Введите логин и пароль.";
                return false;
            }

            try
            {
                DatabaseService database = new DatabaseService(ConnectionSettings.MainConnection);
                DataTable table = database.ExecuteSelect(
                    "SELECT user_id, login, password_hash, role_name FROM app_users WHERE login = @login;",
                    new Dictionary<string, object> { { "@login", login.Trim() } });

                if (table.Rows.Count == 0)
                {
                    errorMessage = "Пользователь не найден.";
                    return false;
                }

                DataRow row = table.Rows[0];
                string storedHash = Convert.ToString(row["password_hash"]);
                string enteredHash = PasswordHasher.ComputeSha256Hash(password);

                if (!string.Equals(storedHash, enteredHash, StringComparison.OrdinalIgnoreCase))
                {
                    errorMessage = "Неверный пароль.";
                    return false;
                }

                UserSession.UserId = Convert.ToInt32(row["user_id"]);
                UserSession.Login = Convert.ToString(row["login"]);
                UserSession.RoleName = Convert.ToString(row["role_name"]);
                return true;
            }
            catch (PostgresException ex)
            {
                errorMessage = "Ошибка PostgreSQL: " + ex.MessageText;
                return false;
            }
            catch (NpgsqlException ex)
            {
                errorMessage = "Ошибка подключения к базе данных: " + BuildExceptionMessage(ex);
                return false;
            }
            catch (Exception ex)
            {
                errorMessage = "Ошибка авторизации: " + BuildExceptionMessage(ex);
                return false;
            }
        }

        private static string BuildExceptionMessage(Exception exception)
        {
            string message = exception.Message;
            Exception current = exception.InnerException;

            while (current != null)
            {
                message += Environment.NewLine + current.GetType().Name + ": " + current.Message;
                current = current.InnerException;
            }

            return message;
        }
    }
}
