using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Security.Cryptography;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Npgsql;

namespace WpfApp1
{
    /// <summary>
    /// Логика взаимодействия для LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        public static string ConnectionString { get; private set; }

        public LoginWindow()
        {
            InitializeComponent();

            btnLogin.Click += BtnLogin_Click;
            btnExit.Click += BtnExit_Click;
        }

        private string GetSha256Hash(string input)
        {
            using (SHA256 sha = SHA256.Create())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(input);
                byte[] hash = sha.ComputeHash(bytes);

                StringBuilder builder = new StringBuilder();

                foreach (byte b in hash)
                    builder.Append(b.ToString("x2"));

                return builder.ToString();
            }
        }

        private void BtnLogin_Click(object sender, RoutedEventArgs e)
        {
            string login = LoginTextBox.Text.Trim();
            string password = PasswordBox.Password.Trim();

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

            string passwordHash = GetSha256Hash(password);

            string connectionString =
                "Host=edu-pg.itiscaf.ru;Port=5432;Database=dbwork;Username=emelyanov_ia;Password=4&U4p#u#1M0";

            try
            {
                using var connection = new NpgsqlConnection(connectionString);
                connection.Open();

                string sql = @"
                    SELECT role_name
                    FROM emelyanov_ia.app_users
                    WHERE login = @login;
                ";

                using var command = new NpgsqlCommand(sql, connection);
                command.Parameters.AddWithValue("@login", login);
                command.Parameters.AddWithValue("@password_hash", passwordHash);

                object result = command.ExecuteScalar();
                
                if (result == null)
                {
                    MessageBox.Show(
                        "Неверный логин или пароль.",
                        "Ошибка входа",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error
                    );
                    return;
                }

                string role = result.ToString();

                MainWindow mainWindow = new MainWindow(role);
                mainWindow.Show();

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Ошибка подключения к базе данных:\n" + ex.Message,
                    "Ошибка",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
            }
        }

        private void BtnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
