using System;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Npgsql;

namespace ZhkhApp
{
    public partial class LoginForm : Form
    {
        private string connectionString = "Host=edu-pg.itiscaf.ru;Port=5432;Database=dbwork;Username=grigoreva_va;Password=3&x28bky7d#;SSL Mode=Disable;";
        private bool isPasswordVisible = false;
        private Button btnTogglePassword;

        public LoginForm()
        {
            InitializeComponent();
            SetupPasswordToggle();
        }

        private void SetupPasswordToggle()
        {
            btnTogglePassword = new Button();
            btnTogglePassword.Text = "👁️";
            btnTogglePassword.Size = new Size(25, 23);
            btnTogglePassword.FlatStyle = FlatStyle.Flat;
            btnTogglePassword.BackColor = Color.Transparent;
            btnTogglePassword.Cursor = Cursors.Hand;
            btnTogglePassword.Click += BtnTogglePassword_Click;
            btnTogglePassword.Location = new Point(txtPassword.Right - 25, txtPassword.Top + 1);
            this.Controls.Add(btnTogglePassword);
            btnTogglePassword.BringToFront();
        }

        private void BtnTogglePassword_Click(object sender, EventArgs e)
        {
            isPasswordVisible = !isPasswordVisible;
            if (isPasswordVisible)
            {
                txtPassword.UseSystemPasswordChar = false;
                btnTogglePassword.Text = "🙈";
            }
            else
            {
                txtPassword.UseSystemPasswordChar = true;
                btnTogglePassword.Text = "👁️";
            }
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            if (string.IsNullOrEmpty(username))
            {
                lblStatus.Text = "Введите имя пользователя!";
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                lblStatus.Text = "Введите пароль!";
                return;
            }

            if (AuthenticateUser(username, password))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                lblStatus.Text = "Неверное имя пользователя или пароль!";
            }
        }

        private bool AuthenticateUser(string username, string password)
        {
            string query = "SELECT * FROM authenticate_user(@username, @password)";

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

                    // Убираем SET app.current_user — он вызывает ошибку
                    // Триггер будет использовать current_user (grigoreva_va)

                    using (var cmd = new NpgsqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@username", username);
                        cmd.Parameters.AddWithValue("@password", password);

                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                MainForm.CurrentUserId = reader.GetInt32(0);
                                MainForm.CurrentRole = reader.GetString(1);
                                MainForm.CurrentUserFullName = reader.GetString(2);
                                MainForm.CurrentUsername = username;
                                MainForm.ConnectionString = connectionString;

                                return true;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка подключения: {ex.Message}");
                }
            }
            return false;
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}