require('dotenv').config();
const jwt = require('jsonwebtoken');
const db = require('../../models/migration');
const User = db.User;

const optionalAuth = async (req, res, next) => {
  try {
    const header = req.header('Authorization');

    // kalau tidak ada token, user dianggap belum login → lanjut aja
    if (!header) {
      req.user = null;
      return next();
    }

    const idToken = header.replace('Bearer ', '');
    const decoded = jwt.verify(idToken, process.env.JWT_SECRET_KEY);

    const user = await User.findByPk(decoded.id);
    if (!user || user.is_suspended) {
      req.user = null;
      return next();
    }

    req.user = user;
    return next();
  } catch (e) {
    // kalau token invalid, tetap lanjut tapi tanpa user
    req.user = null;
    return next();
  }
};

module.exports = optionalAuth;
