const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const {env} = require('../config/env');

function signAccessToken(user) {
  return jwt.sign(
    {
      sub: String(user.id),
      shopId: String(user.shop_id),
      role: user.role_name,
    },
    env.jwt.secret,
    {expiresIn: env.jwt.expiresIn},
  );
}

function createRefreshToken() {
  const token = crypto.randomBytes(48).toString('hex');
  const hash = crypto.createHash('sha256').update(token).digest('hex');
  return {token, hash};
}

function hashToken(token) {
  return crypto.createHash('sha256').update(token).digest('hex');
}

module.exports = {createRefreshToken, hashToken, signAccessToken};
