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

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'wa_tools',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'wa_tools',
  waitForConnections: true,
  connectionLimit: 5,
  charset: 'utf8mb4',
});

async function findUserByEmail(email) {
  const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]);
  return rows[0] || null;
}

async function findUserById(id) {
  const [rows] = await pool.execute('SELECT id, email, display_name, created_at FROM users WHERE id = ?', [id]);
  return rows[0] || null;
}

async function createUser(email, passwordHash, displayName) {
  const [result] = await pool.execute(
    'INSERT INTO users (email, password_hash, display_name) VALUES (?, ?, ?)',
    [email, passwordHash, displayName || null]
  );
  return result.insertId;
}

async function updateLastLogin(id) {
  await pool.execute('UPDATE users SET last_login = NOW() WHERE id = ?', [id]);
}

module.exports = { pool, findUserByEmail, findUserById, createUser, updateLastLogin };
