const jwt = require("jsonwebtoken");
const Session = require("../models/session.model");
const { parseCookieHeader } = require("../utils/cookies");
const { cookieName } = require("../utils/session-cookie");
const { logError } = require("../utils/logger");

async function optionalAuth(req, res, next) {
  const header = req.headers.authorization || "";
  const token = header.startsWith("Bearer ") ? header.slice(7).trim() : null;

  if (token) {
    const jwtSecret = process.env.JWT_SECRET;
    if (!jwtSecret) {
      return next();
    }

    try {
      const decoded = jwt.verify(token, jwtSecret);
      req.user = decoded;
      return next();
    } catch (err) {
      return next();
    }
  }

  try {
    const cookies = parseCookieHeader(req.headers.cookie);
    const sid = cookies[cookieName()];
    if (!sid) return next();

    const session = await Session.getActiveSessionWithUser(sid);
    if (!session) return next();

    req.user = {
      id: session.user_id,
      role: session.role,
      username: session.username,
    };
    req.session_id = session.id;
  } catch (err) {
    logError(req, "middleware.optionalAuth", err);
  }

  return next();
}

module.exports = optionalAuth;
