const { pool } = require('../db/pool');
const { authenticateToken } = require('../auth/auth.service');

const getBearerToken = (value) => {
  if (!value || typeof value !== 'string') return null;
  const trimmed = value.trim();
  if (!trimmed.toLowerCase().startsWith('bearer ')) return null;
  const token = trimmed.slice(7).trim();
  return token || null;
};

const requireAuth = async (req, res, next) => {
  try {
    const token = getBearerToken(req.headers.authorization);
    if (!token) {
      res.status(401).json({ error: 'auth_required' });
      return;
    }

    const user = await authenticateToken(pool, token);
    if (!user) {
      res.status(401).json({ error: 'invalid_token' });
      return;
    }

    req.user = user;
    req.authToken = token;
    next();
  } catch (error) {
    next(error);
  }
};

module.exports = { requireAuth };
