/**
 * VulnBank - Database Operations with intentional vulnerabilities
 *
 * Vulnerabilities:
 * - SQL injection via template literals
 * - SQL injection via string concatenation
 */

const mysql = require('mysql2/promise');

// BLOCK: Hardcoded database password
const pool = mysql.createPool({
  host: 'localhost',
  user: 'vulnbank',
  password: 'password123',
  database: 'vulnbank'
});

/**
 * VULNERABILITY: SQL injection via template literal
 * User input directly interpolated into SQL query
 */
async function getUserById(userId) {
  const connection = await pool.getConnection();
  try {
    // BLOCK: SQL injection - template literal with user input
    const [rows] = await connection.query(
      `SELECT * FROM users WHERE id = '${userId}'`
    );
    return rows[0];
  } finally {
    connection.release();
  }
}

/**
 * VULNERABILITY: SQL injection via string concatenation
 */
async function searchProducts(name) {
  const connection = await pool.getConnection();
  try {
    // BLOCK: SQL injection - string concatenation with user input
    const query = "SELECT * FROM products WHERE name LIKE '%" + name + "%'";
    const [rows] = await connection.query(query);
    return rows;
  } finally {
    connection.release();
  }
}

/**
 * VULNERABILITY: SQL injection in DELETE statement
 */
async function deleteOrder(orderId) {
  const connection = await pool.getConnection();
  try {
    // BLOCK: SQL injection - user input in DELETE query
    await connection.query(`DELETE FROM orders WHERE id = ${orderId}`);
    return true;
  } finally {
    connection.release();
  }
}

/**
 * Safe version for comparison - uses parameterized queries
 */
async function getUserByIdSafe(userId) {
  const connection = await pool.getConnection();
  try {
    // This is the correct approach - parameterized query
    const [rows] = await connection.query(
      'SELECT * FROM users WHERE id = ?',
      [userId]
    );
    return rows[0];
  } finally {
    connection.release();
  }
}

module.exports = {
  getUserById,
  searchProducts,
  deleteOrder,
  getUserByIdSafe
};
