// models/departmentModel.js
const { getDb } = require('../dbPool');

const departmentModel = {
  // 모든 부서 조회 (계층 구조 포함)
  async getAll() {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT d.*,
             p.department_name as parent_name,
             (SELECT COUNT(*) FROM workers w WHERE w.department_id = d.department_id AND w.status = 'active') as worker_count
      FROM departments d
      LEFT JOIN departments p ON d.parent_id = p.department_id
      ORDER BY d.display_order, d.department_name
    `);
    return rows;
  },

  // 활성 부서만 조회
  async getActive() {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT d.*,
             p.department_name as parent_name,
             (SELECT COUNT(*) FROM workers w WHERE w.department_id = d.department_id AND w.status = 'active') as worker_count
      FROM departments d
      LEFT JOIN departments p ON d.parent_id = p.department_id
      WHERE d.is_active = TRUE
      ORDER BY d.display_order, d.department_name
    `);
    return rows;
  },

  // 부서 ID로 조회
  async getById(departmentId) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT d.*,
             p.department_name as parent_name
      FROM departments d
      LEFT JOIN departments p ON d.parent_id = p.department_id
      WHERE d.department_id = ?
    `, [departmentId]);
    return rows[0];
  },

  // 부서 생성
  async create(data) {
    const db = await getDb();
    const { department_name, parent_id, description, is_active, display_order } = data;
    const [result] = await db.query(`
      INSERT INTO departments (department_name, parent_id, description, is_active, display_order)
      VALUES (?, ?, ?, ?, ?)
    `, [department_name, parent_id || null, description || null, is_active !== false, display_order || 0]);
    return result.insertId;
  },

  // 부서 수정
  async update(departmentId, data) {
    const db = await getDb();
    const { department_name, parent_id, description, is_active, display_order } = data;
    const [result] = await db.query(`
      UPDATE departments
      SET department_name = ?, parent_id = ?, description = ?, is_active = ?, display_order = ?
      WHERE department_id = ?
    `, [department_name, parent_id || null, description || null, is_active, display_order || 0, departmentId]);
    return result.affectedRows > 0;
  },

  // 부서 삭제
  async delete(departmentId) {
    const db = await getDb();
    // 하위 부서가 있는지 확인
    const [children] = await db.query('SELECT COUNT(*) as count FROM departments WHERE parent_id = ?', [departmentId]);
    if (children[0].count > 0) {
      throw new Error('하위 부서가 있어 삭제할 수 없습니다.');
    }
    // 소속 작업자가 있는지 확인
    const [workers] = await db.query('SELECT COUNT(*) as count FROM workers WHERE department_id = ?', [departmentId]);
    if (workers[0].count > 0) {
      throw new Error('소속 작업자가 있어 삭제할 수 없습니다. 먼저 작업자를 다른 부서로 이동하세요.');
    }
    const [result] = await db.query('DELETE FROM departments WHERE department_id = ?', [departmentId]);
    return result.affectedRows > 0;
  },

  // 부서별 작업자 조회
  async getWorkersByDepartment(departmentId) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT w.*, d.department_name, u.user_id, u.username
      FROM workers w
      LEFT JOIN departments d ON w.department_id = d.department_id
      LEFT JOIN users u ON u.user_id = w.user_id
      WHERE w.department_id = ?
      ORDER BY w.worker_name
    `, [departmentId]);
    return rows;
  },

  // 작업자 부서 변경
  async moveWorker(userId, departmentId) {
    const db = await getDb();
    const [result] = await db.query(`
      UPDATE workers SET department_id = ? WHERE user_id = ?
    `, [departmentId, userId]);
    return result.affectedRows > 0;
  },

  // 여러 작업자 부서 일괄 변경
  async moveWorkers(userIds, departmentId) {
    const db = await getDb();
    const [result] = await db.query(`
      UPDATE workers SET department_id = ? WHERE user_id IN (?)
    `, [departmentId, userIds]);
    return result.affectedRows;
  }
};

module.exports = departmentModel;
