using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace CarApp
{
    public partial class LoginForm : Form
    {
        string conn = "Host=...";

        public string UserRole { get; private set; }

        TextBox txtLogin = new TextBox();
        TextBox txtPassword = new TextBox();
        Button btnLogin = new Button();

        public LoginForm()
        {
            Text = "Вход";

            txtLogin.Top = 20;
            txtLogin.Left = 20;
            txtLogin.Width = 200;

            txtPassword.Top = 60;
            txtPassword.Left = 20;
            txtPassword.Width = 200;
            txtPassword.PasswordChar = '*';

            btnLogin.Text = "Войти";
            btnLogin.Top = 100;
            btnLogin.Left = 20;

            btnLogin.Click += Login_Click;

            Controls.Add(txtLogin);
            Controls.Add(txtPassword);
            Controls.Add(btnLogin);
        }

        private void Login_Click(object sender, EventArgs e)
        {
            try
            {
                using var c = new NpgsqlConnection(conn);
                c.Open();

                var cmd = new NpgsqlCommand(
                    "SELECT role FROM users WHERE login=@l AND password=@p", c);

                cmd.Parameters.AddWithValue("@l", txtLogin.Text);
                cmd.Parameters.AddWithValue("@p", txtPassword.Text);

                var role = cmd.ExecuteScalar();

                if (role != null)
                {
                    UserRole = role.ToString();
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    MessageBox.Show("Неверный логин или пароль");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
