const passportJWT = require('passport-jwt');
const { query } = require('./dbconnection');
const jwt = require('jsonwebtoken');
const config = require("../conf/config.json");

const {
  secret: tokenSecret,
  expireInAccessToken,
  expireInRefreshToken,
} = require('../conf/config.json').secure.jwt;

var JwtStrategy = passportJWT.Strategy;
var ExtractJwt = passportJWT.ExtractJwt;

var opts = {
  jwtFromRequest: ExtractJwt.fromExtractors([
    ExtractJwt.fromAuthHeaderAsBearerToken(),
    ExtractJwt.fromHeader('authorization'),
    (req) => {
      let token = null;
      if (req && req.cookies) {
        token = req.cookies['auth_token'];
      }
      return token;
    },
  ]),
  secretOrKey: tokenSecret,
};

const verifyUser = async (payload, cb) => {
  const user_id = payload.user_id;

  try {
    const users = await query(
      `SELECT 
        u.user_id,
        u.user_name,
        u.account_id,
        u.dept_id,
        d.dept_name,
        u.is_admin,
        u.is_active,
        u.is_worker
      FROM \`${config.dbName.boas_se}\`.tb_user u
      LEFT JOIN \`${config.dbName.boas_se}\`.tb_dept d 
        ON d.dept_id = u.dept_id
      WHERE u.user_id = ?
        AND u.is_active = 'Y';`,
      [user_id]
  );

    if (users.length) {
      // 배열의 첫 번째 요소만 전달
      const user = users[0];
      cb(null, user);
    } else {
      cb(null, false);
    }
  } catch (error) {
    console.error('Error in verifyUser:', error);
    cb(error, false);
  }
};

const conf = {
  passportConfig(passport) {
    passport.serializeUser((user, cb) => {
      cb(null, user);
    });

    passport.deserializeUser((user, cb) => {
      cb(null, user);
    });
    passport.use(new JwtStrategy(opts, verifyUser));
  },
  createAuthToken(data) {
    var token = jwt.sign(data, tokenSecret, { expiresIn: expireInAccessToken });

    return token;
  },
  createRefreshToken(data) {
    var token = jwt.sign(data, tokenSecret, {
      expiresIn: expireInRefreshToken,
    });

    return token;
  },
};

module.exports = conf;
