/**
 * Department Model
 *
 * departments 테이블 CRUD + 승인권한 관리 (MariaDB)
 */

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

async function getAll() {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT d.*, su.name AS leader_name
     FROM departments d
     LEFT JOIN sso_users su ON d.leader_user_id = su.user_id
     ORDER BY d.display_order ASC, d.department_id ASC`
  );
  return rows;
}

async function getById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT d.*, su.name AS leader_name
     FROM departments d
     LEFT JOIN sso_users su ON d.leader_user_id = su.user_id
     WHERE d.department_id = ?`,
    [id]
  );
  return rows[0] || null;
}

async function create({ department_name, description, display_order }) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO departments (department_name, description, display_order)
     VALUES (?, ?, ?)`,
    [department_name, description || null, display_order || 0]
  );
  return getById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];

  if (data.department_name !== undefined) { fields.push('department_name = ?'); values.push(data.department_name); }
  if (data.description !== undefined) { fields.push('description = ?'); values.push(data.description || null); }
  if (data.display_order !== undefined) { fields.push('display_order = ?'); values.push(data.display_order); }
  if (data.leader_user_id !== undefined) { fields.push('leader_user_id = ?'); values.push(data.leader_user_id || null); }

  if (fields.length === 0) return getById(id);

  values.push(id);
  await db.query(
    `UPDATE departments SET ${fields.join(', ')} WHERE department_id = ?`,
    values
  );
  return getById(id);
}

async function remove(id) {
  const db = getPool();
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();
    // CASCADE가 있지만 방어적으로 명시 삭제
    await conn.query('DELETE FROM dept_approval_authority WHERE department_id = ?', [id]);
    await conn.query('UPDATE users SET department_id = NULL WHERE department_id = ?', [id]);
    await conn.query('DELETE FROM departments WHERE department_id = ?', [id]);
    await conn.commit();
  } catch (e) {
    await conn.rollback();
    throw e;
  } finally {
    conn.release();
  }
}

/* ===== 승인권한 (Approval Authority) ===== */

async function getApprovalAuthorities(departmentId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT aa.*, su.name AS approver_name
     FROM dept_approval_authority aa
     JOIN sso_users su ON aa.approver_user_id = su.user_id
     WHERE aa.department_id = ? AND aa.is_active = TRUE
     ORDER BY aa.approval_type ASC, aa.priority ASC`,
    [departmentId]
  );
  return rows;
}

async function createApprovalAuthority({ department_id, approval_type, approver_user_id, priority }) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO dept_approval_authority (department_id, approval_type, approver_user_id, priority)
     VALUES (?, ?, ?, ?)`,
    [department_id, approval_type, approver_user_id, priority || 1]
  );
  const [rows] = await db.query(
    `SELECT aa.*, su.name AS approver_name
     FROM dept_approval_authority aa
     JOIN sso_users su ON aa.approver_user_id = su.user_id
     WHERE aa.id = ?`,
    [result.insertId]
  );
  return rows[0] || null;
}

async function deleteApprovalAuthority(id) {
  const db = getPool();
  await db.query('DELETE FROM dept_approval_authority WHERE id = ?', [id]);
}

async function getApproversByType(departmentId, approvalType) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT aa.*, su.name AS approver_name
     FROM dept_approval_authority aa
     JOIN sso_users su ON aa.approver_user_id = su.user_id
     WHERE aa.department_id = ? AND aa.approval_type = ? AND aa.is_active = TRUE
     ORDER BY aa.priority ASC`,
    [departmentId, approvalType]
  );
  return rows;
}

module.exports = {
  getAll, getById, create, update, remove,
  getApprovalAuthorities, createApprovalAuthority, deleteApprovalAuthority, getApproversByType
};
