// FILE: src/middleware/requireBearer.js
import jwt from "jsonwebtoken";
import { findUserById } from "../db/models/users.js";

export async function requireBearer(req, res, next) {
  const hdr = req.get("Authorization") || "";
  const m = hdr.match(/^Bearer\s+(.+)$/i);
  if (!m) return res.status(401).json({ error: "Unauthenticated" });
  try {
    const payload = jwt.verify(m[1], process.env.JWT_ACCESS_SECRET, { issuer: "dms-backend" });
    const user = await findUserById(payload.user_id);
    if (!user) return res.status(401).json({ error: "Unauthenticated" });
    req.user = { user_id: user.user_id, username: user.username, email: user.email, first_name: user.first_name, last_name: user.last_name };
    next();
  } catch {
    return res.status(401).json({ error: "Unauthenticated" });
  }
}
