var express = require("express");
const router = express.Router();
const db = require("../../utils/database");

router.post("/insertDepartment", (req, res) => {
  //var code=req.body.code
  var dep = req.body.dep;

  db.getConnection((err, connection) => {
    if (err) {
      console.log("database not connected error: >>>", err);
      throw err;
    }
    console.log("get Connection");
    var query = `insert into finehhdi_eDefect.Department (department) values ("${dep}");`;
    connection.query(query, (err, result) => {
      connection.release();
      //validation for duplicate department
      if (err) {
        if (err.code === "ER_DUP_ENTRY") {
          res.status(409).json({
            message: "Duplicate User",
            results: "Failed",
          });
        } else if (err.code === "ENOTFOUND") {
          res.status(404).json({
            message: "Internet Connection Failed",
            results: "failed",
          });
        } else {
          res.status(401).json({
            message: "dep creation failed",
            results: "Failed",
          });
        }
      } else {
        res.status(200).json({
          message: "dep Created Successfully",
          results: "Success",
        });
      }
    });
    console.log("release Connection");
  });
});

///////
router.get("/getDepartment", (req, res) => {
  console.log("testing =================>");
  db.getConnection((err, connection) => {
    if (err) {
      console.log("database not connected error: >>>", err);
      throw err;
    }
    console.log("get Connection");
    var query = `select * from finehhdi_eDefect.Department order by id desc`;
  
    connection.query(query, (err, result) => {
      connection.release()
      if (err) {
        console.log(err);
        res.status(401).json({
          message: "Some error in type selection",
          results: "Failed",
          department: [],
        });
      } else {
        res.status(201).json({
          message: "type Successfully",
          results: "Success",
          department: result,
        });
      }
    });
    console.log("release Connection");
  });
});

module.exports = router;
