import { Request, Response, NextFunction } from 'express';
import jwt, { JwtPayload } from 'jsonwebtoken';

export function authentificationToken(req: Request, res: Response, next: NextFunction): void {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    res.sendStatus(401);
    return;
  }

  const secret = process.env.ACCESS_TOKEN_SECRET;
  if (!secret) {
    console.error("ACCESS_TOKEN_SECRET is not defined");
    res.sendStatus(500);
    return;
  }

  jwt.verify(token, secret, (err, decoded) => {
    if (err) {
      res.sendStatus(403);
      return;
    }

    (req as any).user = decoded;
    next(); // only call next if everything is valid
  });
}