/**
 * Department Controller
 *
 * 부서 CRUD + 승인권한 관리
 */

const departmentModel = require('../models/departmentModel');

async function getAll(req, res, next) {
  try {
    const departments = await departmentModel.getAll();
    res.json({ success: true, data: departments });
  } catch (err) {
    next(err);
  }
}

async function getById(req, res, next) {
  try {
    const dept = await departmentModel.getById(parseInt(req.params.id));
    if (!dept) {
      return res.status(404).json({ success: false, error: '부서를 찾을 수 없습니다' });
    }
    res.json({ success: true, data: dept });
  } catch (err) {
    next(err);
  }
}

async function create(req, res, next) {
  try {
    const { department_name } = req.body;
    if (!department_name) {
      return res.status(400).json({ success: false, error: '부서명은 필수입니다' });
    }
    const dept = await departmentModel.create(req.body);
    res.status(201).json({ success: true, data: dept });
  } catch (err) {
    next(err);
  }
}

async function update(req, res, next) {
  try {
    const id = parseInt(req.params.id);
    const dept = await departmentModel.update(id, req.body);
    if (!dept) {
      return res.status(404).json({ success: false, error: '부서를 찾을 수 없습니다' });
    }
    res.json({ success: true, data: dept });
  } catch (err) {
    next(err);
  }
}

async function remove(req, res, next) {
  try {
    const id = parseInt(req.params.id);
    await departmentModel.remove(id);
    res.json({ success: true, message: '부서가 삭제되었습니다' });
  } catch (err) {
    next(err);
  }
}

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

async function getApprovalAuthorities(req, res, next) {
  try {
    const departmentId = parseInt(req.params.id);
    const data = await departmentModel.getApprovalAuthorities(departmentId);
    res.json({ success: true, data });
  } catch (err) {
    next(err);
  }
}

async function createApprovalAuthority(req, res, next) {
  try {
    const departmentId = parseInt(req.params.id);
    const { approval_type, approver_user_id } = req.body;
    if (!approval_type || !approver_user_id) {
      return res.status(400).json({ success: false, error: '승인유형과 승인자는 필수입니다' });
    }
    const data = await departmentModel.createApprovalAuthority({
      department_id: departmentId,
      ...req.body
    });
    res.status(201).json({ success: true, data });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ success: false, error: '이미 등록된 승인권한입니다' });
    }
    next(err);
  }
}

async function deleteApprovalAuthority(req, res, next) {
  try {
    const authId = parseInt(req.params.authId);
    await departmentModel.deleteApprovalAuthority(authId);
    res.json({ success: true, message: '승인권한이 삭제되었습니다' });
  } catch (err) {
    next(err);
  }
}

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