// FILE: backend/src/middleware/auth.js
// (ถ้ายังใช้อยู่) ปรับให้สอดคล้อง Bearer + principal
import jwt from "jsonwebtoken";

export function signAccessToken(payload) {
  const { JWT_SECRET = "dev-secret", JWT_EXPIRES_IN = "30m" } = process.env;
  return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN, issuer: "dms-backend" });
}
export function signRefreshToken(payload) {
  const { JWT_REFRESH_SECRET = "dev-refresh", JWT_REFRESH_EXPIRES_IN = "30d" } = process.env;
  return jwt.sign({ ...payload, t: "refresh" }, JWT_REFRESH_SECRET, { expiresIn: JWT_REFRESH_EXPIRES_IN, issuer: "dms-backend" });
}

// ถ้าจะใช้ standalone (ไม่แนะนำถ้ามี authJwt แล้ว)
export function requireAuth(req, res, next) {
  const h = req.headers.authorization || "";
  const m = /^Bearer\s+(.+)$/i.exec(h || "");
  if (!m) return res.status(401).json({ error: "Missing token" });
  try {
    const { JWT_SECRET = "dev-secret" } = process.env;
    const payload = jwt.verify(m[1], JWT_SECRET, { issuer: "dms-backend" });
    req.auth = { user_id: payload.user_id, username: payload.username };
    req.user = req.user || {};
    req.user.user_id = payload.user_id;
    req.user.username = payload.username;
    next();
  } catch {
    return res.status(401).json({ error: "Invalid/Expired token" });
  }
}