var express = require("express");
const router = express.Router();
const db = require("../../utils/database");
const dbFuntion = require("../../utils/dbfunction");
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) => {
    if (err1) {
      console.log(err1);
      res.json({
        error: err1,
      });
    }
    if (data.length < 1) {
     return res.status(404).json({
        message: "user not found some issues in authentication",
      });
    }     
    else {
      bcrypt.compare(password, data[0].password, function (errorr, result) {
        if(result===false){
            return res.status(404).json({
              message: "user not found some issues in authentication",
            });
          }
        if (errorr) {
          console.log('err',errorr);
         return res.status(401).json({
            message: "authfailed in bcr wrong password",
          });
        }
        if (result) {
          console.log('result',result)
          var token = jwt.sign( 
            {
              id:data[0].id,
              username: data[0].username,
              email: data[0].email,
              isAdmin: data[0].isAdmin,
            },
            "pksectret",
            {
              expiresIn: "1h",
            }
          );
          res.status(201).json({
            message: "User Found",
            token: token,
            user: data,
          });
        }
      });
    }
  });
});
module.exports = router;