// backend/models/userModel.js
const db = require('../config/db');
const bcrypt = require('bcryptjs');

const User = {
  /**
   * Creates a new user. For super_admins, institution_id is null.
   * @param {object} userData
   * @param {number|null} userData.institution_id
   * @param {number} userData.role_id
   * @param {string} userData.name
   * @param {string} userData.mobile
   * @param {string} userData.password - The plain-text password.
   * @returns {Promise<object>} The newly created user's ID and mobile.
   */
  create: async ({ institution_id, role_id, name, mobile, password }) => {
    const salt = await bcrypt.genSalt(10);
    const password_hash = await bcrypt.hash(password, salt);

    const sql = 'INSERT INTO users (institution_id, role_id, name, mobile, password_hash, status) VALUES (?, ?, ?, ?, ?, "active")';
    const [result] = await db.query(sql, [institution_id, role_id, name, mobile, password_hash]);
    return { id: result.insertId, mobile };
  },

  /**
   * Finds a user by their mobile. Includes role name for authentication/authorization.
   * @param {string} mobile
   * @returns {Promise<object|undefined>} User object including password_hash and role.
   */
  findByMobile: async (mobile) => {
    const sql = `
      SELECT u.id, u.institution_id, u.name, u.mobile, u.password_hash, u.status, r.name as role 
      FROM users u
      JOIN roles r ON u.role_id = r.id
      WHERE u.mobile = ?
    `;
    const [rows] = await db.query(sql, [mobile]);
    return rows[0];
  },

  /**
   * Finds a user by their ID, excluding the password.
   * @param {number} id
   * @returns {Promise<object|undefined>} User object without password.
   */
  findById: async (id) => {
    const sql = `
      SELECT u.id, u.institution_id, u.name, u.mobile, u.status, r.name as role
      FROM users u
      JOIN roles r ON u.role_id = r.id
      WHERE u.id = ?
    `;
    const [rows] = await db.query(sql, [id]);
    return rows[0];
  },
  
  /**
   * Finds all users for a given institution.
   * @param {number} institution_id
   * @returns {Promise<Array<object>>}
   */
  findAllByInstitution: async (institution_id) => {
    const sql = `
      SELECT u.id, u.name, u.mobile, u.status, r.name as role
      FROM users u
      JOIN roles r ON u.role_id = r.id
      WHERE u.institution_id = ?
      ORDER BY u.name ASC
    `;
    const [rows] = await db.query(sql, [institution_id]);
    return rows;
  },

  /**
   * Updates a user's status.
   * @param {number} id
   * @param {'active' | 'inactive'} status
   * @returns {Promise<boolean>}
   */
  setStatus: async (id, status) => {
    const [result] = await db.query('UPDATE users SET status = ? WHERE id = ?', [status, id]);
    return result.affectedRows > 0;
  }
};

module.exports = User;