using System;
using System.Windows.Forms;
using Npgsql;
using RestaurantApp.DAL;

namespace RestaurantApp
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
            btnLogin.Click += BtnLogin_Click;
            btnCancel.Click += (s, e) => Application.Exit();
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtLogin.Text))
            {
                MessageBox.Show("Введите логин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                using (var conn = Database.GetConnection())
                using (var cmd = new NpgsqlCommand(
                    "SELECT full_name, role FROM app_user WHERE login = @login", conn))
                {
                    cmd.Parameters.AddWithValue("login", txtLogin.Text);

                    using (var r = cmd.ExecuteReader())
                    {
                        if (r.Read())
                        {
                            Program.CurrentUser = r.GetString(0);
                            Program.CurrentRole = r.GetString(1);

                            this.Hide();
                            var mainForm = new MainForm();
                            mainForm.Closed += (s, args) => this.Close();
                            mainForm.Show();
                        }
                        else
                        {
                            MessageBox.Show("Неверный логин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка подключения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}