const pool = require("../db/pool");

exports.ROLES = {
  SYSTEM_ADMIN: "system_admin",
  USER: "user",
}

exports.findByUsername = async (username) => {
  const result = await pool.query("SELECT * FROM users WHERE username = $1", [username]);
  return result.rows[0];
};

exports.createUser = async (username, hashedPassword, name) => {
  const result = await pool.query(
    `INSERT INTO users (username, password, name, role)
     VALUES ($1, $2, $3, $4)
     RETURNING id, username, name, role`,
    [username, hashedPassword, name, exports.ROLES.USER]
  );
  return result.rows[0];
};


exports.getAllUsers = async () => {
  const result = await pool.query("SELECT id, username, name, role, display_name FROM users ORDER BY id ASC");
  return result.rows;
};

exports.getUserById = async (id) => {
  const result = await pool.query(
    "SELECT id, username, name, role, display_name FROM users WHERE id = $1",
    [id]
  );
  return result.rows[0];
};

exports.updateUserProfile = async (id, updates) => {
  const { display_name } = updates;
  const result = await pool.query(
    `UPDATE users 
     SET display_name = COALESCE($1, display_name)
     WHERE id = $2 
     RETURNING id, username, name, role, display_name`,
    [display_name, id]
  );
  return result.rows[0];
};

exports.updateUserPassword = async (id, hashedPassword) => {
  const result = await pool.query(
    `UPDATE users 
     SET password = $1 
     WHERE id = $2 
     RETURNING id`,
    [hashedPassword, id]
  );
  return result.rows[0];
};

exports.getUserPasswordHash = async (id) => {
  const result = await pool.query(
    "SELECT password FROM users WHERE id = $1",
    [id]
  );
  return result.rows[0]?.password;
};


exports.updateUserRole = async (id, role) => {
  const result = await pool.query(
    `UPDATE users 
     SET role = $1 
     WHERE id = $2 
     RETURNING id, username, name, role`,
    [role, id]
  );
  return result.rows[0];
};


exports.deleteUser = async (id) => {
  const result = await pool.query(
    `DELETE FROM users WHERE id = $1 RETURNING id`,
    [id]
  );
  return result.rowCount;
};


exports.checkIfUserExists = async (username) => {
  const result = await pool.query(
    "SELECT COUNT(*) FROM users WHERE username = $1",
    [username]
  );
  return result.rows[0].count > 0;
}


