const jwt = require('jsonwebtoken');
const fs  = require('fs');
const path = require('path');

const DB_PATH = path.join(__dirname, '../data/users.json');

module.exports = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token' });
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    // Attach role from users file if available
    try {
      if (fs.existsSync(DB_PATH)) {
        const users = JSON.parse(fs.readFileSync(DB_PATH));
        const user  = users.find(u => u.username === decoded.username);
        if (user) { decoded.role = user.role; decoded.id = user.id; }
      }
    } catch {}
    if (!decoded.role) decoded.role = 'admin'; // fallback for existing tokens
    req.user = decoded;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
};