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

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 q1 = `SELECT u.user_id, u.user_pw, u.user_name, u.account_id, a.account_name, d.dept_name, u.is_admin, u.is_active, u.is_worker FROM \`${config.dbName.boas_se}\`.tb_user AS u, \`${config.dbName.boas_se}\`.tb_dept AS d, \`${config.dbName.boas_se}\`.tb_account AS a WHERE u.dept_id = d.dept_id AND u.account_id = a.account_id;`;
  const q2 = `SELECT dept_id, dept_name FROM \`${config.dbName.boas_se}\`.tb_dept;`;
  const q3 = `SELECT account_id, account_name FROM \`${config.dbName.boas_se}\`.tb_account;`;
  const userList = await query(q1);
  const deptList = await query(q2);
  const accountList = await query(q3);
  const ret = { userList, deptList, accountList };
  console.log(ret);
  res.json(ret);
});

router.post("/info", authMiddleware, adminMiddleware, async (req, res) => {
  const user_id = req.body.user_id;
  const user_pw = req.body.user_pw;
  const user_name = req.body.user_name;
  const dept_id = req.body.dept_id;
  const account_id = req.body.account_id;
  const is_admin = req.body.is_admin;
  const is_active = req.body.is_active;
  const nation = req.body.nation;
  const is_worker = req.body.is_worker;
  console.log(
    user_id,
    user_pw,
    user_name,
    dept_id,
    account_id,
    is_admin,
    is_active,
    nation,
    is_worker
  );

  var ist_param = {};
  if (user_id) ist_param.user_id = user_id;
  else {
    const msg = "User ID is required.";
    console.log(msg);
    res.status(500).json(msg);
    return;
  }
  if (user_pw) ist_param.user_pw = user_pw;
  if (user_name) ist_param.user_name = user_name;
  if (dept_id) ist_param.dept_id = dept_id;
  if (account_id) ist_param.account_id = account_id;
  if (is_admin) ist_param.is_admin = is_admin;
  if (is_active) ist_param.is_active = is_active;
  if (nation) upt_pist_paramaram.nation = nation;
  if (is_worker) ist_param.is_worker = is_worker;

  try {
    const result = await query(
      `INSERT INTO \`${config.dbName.boas_se}\`.tb_user 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 user_id = req.body.user_id;
  const user_pw = req.body.user_pw;
  const user_name = req.body.user_name;
  const dept_id = req.body.dept_id;
  const account_id = req.body.account_id;
  const is_admin = req.body.is_admin;
  const is_active = req.body.is_active;
  const nation = req.body.nation;
  const is_worker = req.body.is_worker;
  console.log(
    user_id,
    user_pw,
    user_name,
    dept_id,
    account_id,
    is_admin,
    is_active,
    nation,
    is_worker
  );

  var upt_param = {};
  if (user_pw) upt_param.user_pw = user_pw;
  if (user_name) upt_param.user_name = user_name;
  if (dept_id) upt_param.dept_id = dept_id;
  if (account_id) upt_param.account_id = account_id;
  if (is_admin) upt_param.is_admin = is_admin;
  if (is_active) upt_param.is_active = is_active;
  if (nation) upt_param.nation = nation;
  if (is_worker) ist_param.is_worker = is_worker;

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

  if (user_cnt == 0) {
    const msg = `User[${user_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_user SET ? WHERE user_id = ?;`,
      [upt_param, user_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 user_id = req.body.user_id;

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

  var msg = "";
  var ret_code = 1000;

  if (user_cnt == 0) {
    msg = `Available ID`;
  } else {
    msg = `This ID[${user_id}] is already taken.`;
    ret_code = 0;
    res.status(409);
  }

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

router.get("/workerUserList", async (req, res) => {
  const q1 = `SELECT u.user_id, u.user_name, u.account_id, a.account_name, d.dept_name, u.is_admin, u.is_active, u.is_worker FROM \`${config.dbName.boas_se}\`.tb_user AS u, \`${config.dbName.boas_se}\`.tb_dept AS d, \`${config.dbName.boas_se}\`.tb_account AS a WHERE u.dept_id = d.dept_id AND u.account_id = a.account_id AND u.is_worker = 'Y';`;
  const userList = await query(q1);
  const ret = { userList };
  console.log(ret);
  res.json(ret);
});

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

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

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

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

module.exports = router;
