import jwt from 'jsonwebtoken'
import { Response, NextFunction } from 'express'

if (!process.env.APP_SECRET) {
  throw Error('App secret (APP_SECRET) must be set in the .env file')
}

export const authenticate = (req: any, res: Response, next: NextFunction) => {
  const { token } = req.cookies
  if (token) {
    const verifiedToken: any = jwt.verify(token, process.env.APP_SECRET || '')
    const { userId } = verifiedToken
    req.userId = userId
  }
  next()
}
