var express = require("express");
const router = express.Router();
const db = require("../../utils/database");
const dbFuntion = require("../../utils/dbfunctions");
const bcrypt = require("bcrypt");
const { response } = require("express");
var jwt = require("jsonwebtoken");

router.post("/login", (req, res) => {
  var email = req.body.email;
  var password = req.body.password;
  console.log(email, password);

  db.query(`select * from finehhdi_fineAD.users where email="${email}"`, (err1, data) => {
    console.log("1.error and data ==>", err1, data);
    // if(err1 === null){
    //   console.log("null error");
    //   res.status(403).send({
    //     message: "Please input correct email a& password"
    //   })
    // }
    if (err1) {
      console.log("2.error from err1====>",err1);
      res.json({
        error: err1,
      });
    }
    if (data.length < 1) {
      console.log("3.log from data.length ====>");
      res.status(404).json({
        message: "user not found some issues in authentication",
      });
    } else {
      bcrypt.compare(password, data[0].password, function (errorr, result) {
        console.log("4.log from compare bcrypt ====>", errorr, result);
        if(result === false){
          console.log("5a.error from result =====>",errorr);
          res.status(401).send({
            message: "authfailed in bcr wrong password",
          });
        }
        if (errorr) {
          console.log("5b.error from errorrrrrrr =====>",errorr);
          // res.send({message: "wrong password"})
          res.status(401).send({
            message: "authfailed in bcr wrong password",
          });
        }
        if (result) {
          var token = jwt.sign(
            {
              id: data[0].id,
              username: data[0].username,
              email: data[0].email,
              isAdmin:data[0].isAdmin,
              ofsRole: data[0].ofsRole,
              bosRole: data[0].bosRole,
              defectRole: data[0].defectRole,
              cilRole:data[0].cilRole,
              clRole: data[0].clRole,
              ofsValue: data[0].ofsValue,
              deptName: data[0].DepartName
            },
            "pksectret",
            {
              expiresIn: "1h",
            }
          );
          res.status(201).json({
            message: "User Found",
            token: token,
            user: data,
          });
        }
      });
    }
  });
});
module.exports = router;