const express = require("express");
const router = express.Router();
const { query } = require("../mods/dbconnection");
const config = require("../conf/config.json");
const moment = require("moment");

const authMiddleware = require("../middleware/authMiddleware");
const adminMiddleware = require("../middleware/adminMiddleware");

// 코드(숫자),의미,상세 설명
// 1000,SUCCESS,모든 작업 정상 처리
// 2001,EMPTY_INPUT,입력값이 없음
// 2002,NOT_FOUND,내용을 찾을 수 없음
// 2003,DUPLICATED,중복된 내용존재 존재함

router.get("/", authMiddleware, adminMiddleware, async (req, res) => {
  const deptList = await query(
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_dept;`,
  );
  const ret = { deptList };
  console.log(ret);
  res.json(ret);
});

router.post("/info", async (req, res) => {
  const dept_name = req.body.dept_name;
  const dept_info = req.body.dept_info;
  const is_active = req.body.is_active;
  console.log(dept_name, dept_info, is_active);

  let dept_id = "dept_001";

  try {
    // dept_ 형식만 조회
    const deptList = await query(
      `
      SELECT dept_id
      FROM \`${config.dbName.boas_se}\`.tb_dept
      WHERE dept_id LIKE 'dept_%'
      ORDER BY CAST(SUBSTRING_INDEX(dept_id, '_', -1) AS UNSIGNED) DESC
      LIMIT 1;
      `
    );

    // 기존 dept_XXX 데이터가 있으면 다음 번호 생성
    if (deptList.length > 0) {
      const lastNumber = parseInt(
        deptList[0].dept_id.split("_")[1],
        10
      );

      dept_id =
        "dept_" +
        String(lastNumber + 1).padStart(3, "0");
    }

    console.log(dept_id);

    const ist_param = {
      dept_id,
    };

    if (dept_name) ist_param.dept_name = dept_name;
    if (dept_info) ist_param.dept_info = dept_info;
    if (is_active !== undefined) ist_param.is_active = is_active;

    const result = await query(
      `INSERT INTO \`${config.dbName.boas_se}\`.tb_dept SET ?;`,
      [ist_param]
    );

    console.log(result);

    res.json(result);

  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});

router.put("/info", authMiddleware, adminMiddleware, async (req, res) => {
  const dept_id = req.body.dept_id;
  const dept_name = req.body.dept_name;
  const dept_info = req.body.dept_info;
  const is_active = req.body.is_active;
  console.log(dept_id, dept_name, dept_info, is_active);

  var upt_param = {};
  if (!dept_id) {
    const msg = "Department ID is required.";
    console.log(msg);
    res.status(500).json(msg);
    return;
  }
  if (dept_name) upt_param.dept_name = dept_name;
  if (dept_info) upt_param.dept_info = dept_info;
  if (is_active) upt_param.is_active = is_active;

  const dept_cnt = await query(
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_dept WHERE dept_id = ?;`,
    [dept_id],
  );

  if (dept_cnt == 0) {
    const msg = `Department[${dept_id}] not found.`;
    console.log(msg);
    res.status(404).json({ msg });
    return;
  }

  console.log(upt_param);

  try {
    const result = await query(
      `UPDATE \`${config.dbName.boas_se}\`.tb_dept SET ? WHERE dept_id = ?;`,
      [upt_param, dept_id],
    );
    console.log(result);
    res.json(result);
  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});


router.post("/check", authMiddleware, adminMiddleware, async (req, res) => {
  const dept_name = req.body.dept_name;

  const dept_cnt = await query(
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_dept WHERE dept_name = ?;`,
    [dept_name],
  );

  var msg = "";
  var ret_code = 1000;

  if (dept_cnt == 0) {
    msg = `Available Name`;
  } else {
    msg = `This name[${dept_name}] is already taken.`;
    ret_code = 0;
    res.status(409);
  }

  console.log(ret_code, msg);
  res.json({ ret_code, msg });
});

router.delete("/delete", authMiddleware, adminMiddleware, async (req, res) => {
  const dept_id = req.body.dept_id;

  try {
    const dept_cnt = await query(
      `SELECT * FROM \`${config.dbName.boas_se}\`.tb_dept WHERE dept_id = ?;`,
      [dept_id],
    );

    if(dept_cnt === 0){
      const msg = `Dept[${dept_id}] not found.`;
      console.log(msg);
      res.status(404).json({ msg });
      return;
    }

    const result = await query(
      `DELETE FROM \`${config.dbName.boas_se}\`.tb_dept WHERE dept_id = ?;`,
      [dept_id],
    );
    console.log(result);
    res.json(result);
  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});
module.exports = router;
