const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const config = require('../config')

function hashPasswordLegacy(password, salt) {
  return crypto.createHash('sha256').update(String(password) + ':' + salt).digest('hex')
}

function hashPassword(password) {
  return bcrypt.hashSync(password, 10)
}

function verifyPassword(password, hash) {
  return bcrypt.compareSync(password, hash)
}

function randomHex(bytes) {
  return crypto.randomBytes(bytes).toString('hex')
}

function signUser(user) {
  return jwt.sign({ type: 'user', user_id: user.user_id, openid: user.openid }, config.jwt.secret, { expiresIn: config.jwt.expiresIn })
}

function signAdmin(admin) {
  return jwt.sign({ type: 'admin', admin_id: admin.admin_id, username: admin.username, role: admin.role }, config.jwt.adminSecret, { expiresIn: config.jwt.expiresIn })
}

function readBearer(headers) {
  const auth = headers.authorization || headers.Authorization || ''
  const match = auth.match(/^Bearer\s+(.+)$/i)
  return match ? match[1] : ''
}

module.exports = { hashPassword, hashPasswordLegacy, verifyPassword, randomHex, signUser, signAdmin, readBearer }
