// middleware/authClient.js
const jwt = require('jsonwebtoken');

const verifyClientToken = (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).json({
      success: false,
      error: 'No token provided'
    });
  }

  const [type, token] = authHeader.split(' ');

  if (type !== 'Bearer' || !token) {
    return res.status(401).json({
      success: false,
      error: 'Invalid token format'
    });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // ✅ CANONICAL AUTH CONTEXT
    req.user = {
      userId: Number(decoded.userId),
      organizationId: Number(decoded.organizationId),
      role: decoded.role
    };

    next();
  } catch (err) {
    return res.status(401).json({
      success: false,
      error: 'Invalid or expired token'
    });
  }
};

module.exports = verifyClientToken;
