using Npgsql;
using System;
using System.Data;
using System.Windows;
using WpfApp1.Helpers;

namespace WpfApp1
{
    public partial class LoginWindow : Window
    {
        private const string Conn = "Host=80.250.189.52;Port=5432;Database=dbwork;Username=kotov_aa;Password=0$s%MB3&F6#";

        public LoginWindow()
        {
            InitializeComponent();
        }

        private void BtnLogin_Click(object sender, RoutedEventArgs e)
        {
            string login = txtLogin.Text.Trim();
            string pass = txtPassword.Password;

            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(pass))
            {
                lblError.Text = "Заполните все поля";
                return;
            }

            try
            {
                string sql = "SELECT id, username, role, password_hash FROM Users WHERE username = @login";
                using var conn = new NpgsqlConnection(Conn);
                conn.Open();
                using var cmd = new NpgsqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@login", login);

                DataTable dt = new DataTable();
                new NpgsqlDataAdapter(cmd).Fill(dt);

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

                DataRow row = dt.Rows[0];
                string storedHash = row["password_hash"].ToString();

                if (PasswordHelper.VerifyPassword(pass, storedHash))
                {
                    AppSession.UserId = Convert.ToInt32(row["id"]);
                    AppSession.Username = row["username"].ToString();
                    AppSession.Role = row["role"].ToString();

                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();
                    this.Close();
                }
                else
                {
                    lblError.Text = "Неверный пароль";
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "Ошибка: " + ex.Message;
            }
        }
    }
}