using System.Windows.Forms;

namespace ToyStoreApp;

public sealed partial class LoginForm : Form
{
    private readonly DatabaseClient _db;

    public LoginForm(DatabaseClient db)
    {
        _db = db;
        InitializeComponent();
    }

    private void LoginButton_Click(object? sender, EventArgs e)
    {
        var user = _db.Authenticate(loginTextBox.Text.Trim(), passwordTextBox.Text);
        if (user is null)
        {
            MessageBox.Show("Неверный логин или пароль.", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        OpenProducts(user);
    }

    private void GuestButton_Click(object? sender, EventArgs e)
    {
        OpenProducts(new AppUser(0, "Гость", "Гость"));
    }

    private void OpenProducts(AppUser user)
    {
        Hide();
        using var form = new ProductListForm(_db, user);
        form.ShowDialog(this);
        passwordTextBox.Clear();
        Show();
    }
}