import { safeEqual } from '../libs/auth.js';

const getBearerToken = (authorization = '') => {
  const [scheme, token] = authorization.split(' ');
  return scheme?.toLowerCase() === 'bearer' ? token : '';
};

const requireInternalToken = (req, res, next) => {
  const expectedToken = process.env.PPAI_INTERNAL_API_TOKEN;
  const providedToken = req.get('x-internal-token') || getBearerToken(req.get('authorization'));

  if (expectedToken && safeEqual(providedToken, expectedToken)) {
    return next();
  }

  return res.unauthorized('Invalid internal token');
};

export default requireInternalToken;
