const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const authentication = require('../../authentication')

module.exports.isAdmin = async (socket, next) => {
  try {
    const token = socket.handshake?.auth?.token
    if (!token) throw new Error('unauthenticated')

    // verifies secret and checks if the token is expired
    const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
    if (!decodedToken) throw new Error('unauthorized')

    // find user
    const user = await User.findById(decodedToken._id)
    if (!user || !user.scope.includes('admin')) throw new Error('unauthorized')

    socket.userId = decodedToken._id.toString()
    return next()
  } catch (e) {
    // console.log('ws user middleware error --- ', e)
    next(new Error(e))
  }
}

module.exports.isUser = async (socket, next) => {
  try {
    const token = socket.handshake?.auth?.token
    if (!token) throw new Error('unauthenticated')

    // verifies secret and checks if the token is expired
    const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
    if (!decodedToken) throw new Error('unauthorized')

    // find user
    const user = await User.findById(decodedToken._id)
    if (!user || !user.scope.includes('user')) throw new Error('unauthorized')

    socket.userId = decodedToken._id.toString()
    return next()
  } catch (e) {
    // console.log('ws user middleware error --- ', e)
    next(new Error(e))
  }
}

module.exports.isAgent = async (socket, next) => {
  try {
    const token = socket.handshake?.auth?.token
    if (!token) throw new Error('unauthenticated')

    // verifies secret and checks if the token is expired
    const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
    if (!decodedToken) throw new Error('unauthorized')

    // find user
    const user = await User.findById(decodedToken._id)
    if (!user || !user.scope.includes('user')) throw new Error('unauthorized')
    if (!user.isAgent) throw new Error('شما نماینده نیستید')

    socket.userId = decodedToken._id.toString()
    socket.agentId = user.representation_id.toString()
    return next()
  } catch (e) {
    next(new Error(e))
  }
}
