using Microsoft.EntityFrameworkCore;
using moduleExamen.Data;
using moduleExamen.Helpers;

namespace moduleExamen.Forms
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
            AppStyles.ApplyIcon(this);

            if (File.Exists(AppStyles.LogoPath))
                logoPictureBox.Image = Image.FromFile(AppStyles.LogoPath);
        }

        private void LoginButton_Click(object? sender, EventArgs e)
        {
            var login = loginTextBox.Text.Trim();
            var password = passwordTextBox.Text.Trim();

            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("Введите логин и пароль.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                using var context = new SportShopContext();
                var user = context.Users
                    .Include(u => u.IdRoleNavigation)
                    .FirstOrDefault(u => u.Login == login && u.Password == password);

                if (user == null)
                {
                    MessageBox.Show("Неверный логин или пароль.", "Ошибка авторизации",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                SessionManager.CurrentUser = user;
                var productForm = new ProductListForm();
                productForm.Show();
                Hide();
                productForm.FormClosed += (_, _) =>
                {
                    SessionManager.CurrentUser = null;
                    loginTextBox.Clear();
                    passwordTextBox.Clear();
                    Show();
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка подключения к базе данных:\n{ex.Message}",
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GuestButton_Click(object? sender, EventArgs e)
        {
            SessionManager.CurrentUser = null;
            var productForm = new ProductListForm();
            productForm.Show();
            Hide();
            productForm.FormClosed += (_, _) => Show();
        }
    }
}
