text: /* eslint-disable camelcase */
  /* eslint-disable consistent-return */
  /* eslint-disable no-console */
  import bcrypt from "bcrypt";
  import Sequelize from "sequelize";
  import jwtSecret from "./jwtConfig";
  
  const BCRYPT_SALT_ROUNDS = 12;
  // eslint-disable-next-line prefer-destructuring
  const Op = Sequelize.Op;
  
  const passport = require("passport");
  const LocalStrategy = require("passport-local").Strategy;
  const JWTstrategy = require("passport-jwt").Strategy;
  const ExtractJWT = require("passport-jwt").ExtractJwt;
  const { User } = require("../sequelize");
  
  var sql = require("../routes/db");
  
  passport.use(
    "register",
    new LocalStrategy(
      {
        usernameField: "userName",
        passwordField: "password",
        passReqToCallback: true,
        session: false,
      },
      (req, userName, password, done) => {
        // console.log("===================================")
        // console.log(userName);
        // console.log(req.body.email);
        // console.log("===================================")
  
        try {
          var columns = [userName];
          sql("GET", "SELECT * FROM users where userName = ? ", columns).then(function (result) {
            //검색된 유저 정보가 없으면
            if (result.row.length > 0) {
              console.log("userName already taken");
              return done(null, false, {
                message: "userName already taken",
              });
            } else {
              bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then((hashedPassword) => {
                var columns = [req.body.email, userName, hashedPassword];
  
                var sqlQuery = "INSERT INTO dev.users (email,userName,password) VALUES (?,?,?)";
  
                sql("INSERT", sqlQuery, columns).then(function (result) {
                  //검색된 유저 정보가 없으면
                  console.log(result.state);
                  return done(null, result.state);
                });
              });
            }
          });
          
        } catch (err) {
          done(err);
        }
  
        // try {
        //   User.findOne({
        //     where: {
        //       [Op.or]: [
        //         {
        //           userName,
        //         },
        //         { email: req.body.email },
        //       ],
        //     },
        //   }).then((user) => {
        //     if (user != null) {
        //       console.log("userName or email already taken");
        //       return done(null, false, {
        //         message: "userName or email already taken",
        //       });
        //     }
        //     bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then((hashedPassword) => {
        //       User.create({
        //         userName,
        //         password: hashedPassword,
        //         email: req.body.email,
        //       }).then((user) => {
        //         console.log("user created");
        //         return done(null, user);
        //       });
        //     });
        //   });
        // } catch (err) {
        //   return done(err);
        // }
      }
    )
  );
  
  passport.use(
    "login",
    new LocalStrategy(
      {
        usernameField: "userName",
        passwordField: "password",
        session: false,
      },
      (userName, password, done) => {
        console.log("Local Strategy");
        try {
          var columns = [userName];
          sql("GET", "SELECT * FROM users where userName = ? ", columns).then(function (result) {
            //검색된 유저 정보가 없으면
            if (result.row.length === 0) {
              return done(null, false, { message: "bad userName" });
            }
  
            bcrypt.compare(password, result.row[0].password).then((response) => {
              if (response !== true) {
                console.log("passwords do not match");
                return done(null, false, { message: "passwords do not match" });
              }
              console.log("user found & authenticated");
              return done(null, result.row[0]);
            });
          });
        } catch (err) {
          done(err);
        }
      }
    )
  );
  
  const opts = {
    jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme("JWT"),
    secretOrKey: jwtSecret.secret,
  };
  
  //jwt를 복호화해서 먼저 id를 가져온다음에, 이 아이디로 user의 정보를 확인한다
  passport.use(
    "jwt",
    new JWTstrategy(opts, (jwt_payload, done) => {
      console.log("JWT Strategy");
  
      try {
        var columns = [jwt_payload.id];
        sql("GET", "SELECT * FROM users where id = ? ", columns).then(function (result) {
          console.log("DB Query Test");
  
          //검색된 유저 정보가 없으면
          if (result.row.length === 0) {
            console.log("user not found in db");
            done(null, false);
          } else {
            console.log("user found in db in passport");
            done(null, result.row[0]);
          }
        });
      } catch (err) {
        done(err);
      }
    })
  );
  
  /*
  
  module.exports = () => {
    // Local Strategy
    passport.use(
      new LocalStrategy(
        {
          userNameField: 'email',
          passwordField: 'password',
        },
        function (email, password, done) {
          // 이 부분에선 저장되어 있는 User를 비교하면 된다.
          return UserModel.findOne({
            where: { email: email, password: password },
          })
            .then((user) => {
              if (!user) {
                return done(null, false, {
                  message: 'Incorrect email or password.',
                });
              }
              return done(null, user, { message: 'Logged In Successfully' });
            })
            .catch((err) => done(err));
        },
      ),
    );
  
    //JWT Strategy
    passport.use(
      new JWTStrategy(
        {
          jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
          secretOrKey: process.env.JWT_SECRET,
        },
        function (jwtPayload, done) {
          return UserModel.findOneById(jwtPayload.id)
            .then((user) => {
              return done(null, user);
            })
            .catch((err) => {
              return done(err);
            });
        },
      ),
    );
  };
  
  */
  