using System.Data.SqlClient;
using UI.Database;

namespace UI.Services
{
    public class AuthService
    {
        public static bool Login(string email, string senha)
        {
            using (SqlConnection conn = DatabaseService.GetConnection())
            {
                conn.Open();

                string sql =
                @"SELECT Id
                  FROM Usuarios
                  WHERE Email = @Email
                  AND SenhaHash = @Senha
                  AND Status = 1";

                SqlCommand cmd = new SqlCommand(sql, conn);

                cmd.Parameters.AddWithValue("@Email", email);
                cmd.Parameters.AddWithValue("@Senha", senha);

                object result = cmd.ExecuteScalar();

                if (result != null)
                {
                    int userId = (int)result;

                    AtualizarUltimoLogin(conn, userId);

                    return true;
                }

                return false;
            }
        }

        private static void AtualizarUltimoLogin(SqlConnection conn, int userId)
        {
            string update =
            @"UPDATE Usuarios
              SET UltimoLogin = GETDATE()
              WHERE Id = @Id";

            SqlCommand cmd = new SqlCommand(update, conn);

            cmd.Parameters.AddWithValue("@Id", userId);

            cmd.ExecuteNonQuery();
        }
    }
}