const { getPool } = require('./partnerModel');
const bcrypt = require('bcrypt');

async function findByCompany(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT user_id, username, name, role, partner_company_id, account_expires_at, is_active, created_at
     FROM sso_users WHERE partner_company_id = ?
     ORDER BY name`, [companyId]);
  return rows;
}

async function findById(userId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT user_id, username, name, role, partner_company_id, account_expires_at, is_active, created_at
     FROM sso_users WHERE user_id = ?`, [userId]);
  return rows[0] || null;
}

async function create(data) {
  const db = getPool();
  const hash = await bcrypt.hash(data.password, 10);
  const [result] = await db.query(
    `INSERT INTO sso_users (username, password_hash, name, role, partner_company_id, account_expires_at, is_active)
     VALUES (?, ?, ?, 'user', ?, ?, TRUE)`,
    [data.username, hash, data.name, data.partner_company_id,
     data.account_expires_at || null]);
  return findById(result.insertId);
}

async function update(userId, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.name !== undefined) { fields.push('name = ?'); values.push(data.name); }
  if (data.account_expires_at !== undefined) { fields.push('account_expires_at = ?'); values.push(data.account_expires_at || null); }
  if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
  if (data.password) {
    const hash = await bcrypt.hash(data.password, 10);
    fields.push('password_hash = ?');
    values.push(hash);
  }
  if (fields.length === 0) return findById(userId);
  values.push(userId);
  await db.query(`UPDATE sso_users SET ${fields.join(', ')} WHERE user_id = ?`, values);
  return findById(userId);
}

async function grantDefaultPermissions(userId) {
  const db = getPool();
  const pages = ['purchasing_partner_portal', 'purchasing_partner_checkin'];
  for (const page of pages) {
    await db.query(
      `INSERT INTO user_page_permissions (user_id, page_name, can_access)
       VALUES (?, ?, TRUE)
       ON DUPLICATE KEY UPDATE can_access = TRUE`,
      [userId, page]);
  }
}

module.exports = { findByCompany, findById, create, update, grantDefaultPermissions };
