const { getSessionUser, COOKIE_NAME, publicUser } = require('../services/authService');
const { getDb, getSetting } = require('../db/database');

function getSingleModeUser() {
  if (getSetting('auth_mode') !== 'single') return null;
  const userId = getSetting('default_user_id');
  if (!userId) return null;
  const row = getDb().prepare(
    "SELECT id, username, display_name, role, must_change_password, first_login FROM users WHERE id = ? AND role = 'user'"
  ).get(userId);
  return row ? publicUser(row) : null;
}

function requireAuth(req, res, next) {
  // Single-user mode: bypass session entirely, auto-attach the default user
  const singleUser = getSingleModeUser();
  if (singleUser) {
    req.user = singleUser;
    req.singleUserMode = true;
    return next();
  }

  const user = getSessionUser(req.cookies?.[COOKIE_NAME]);
  if (!user) return res.status(401).json({ error: 'Not authenticated' });
  req.user = user;
  next();
}

function requireUser(req, res, next) {
  if (!['user', 'admin'].includes(req.user?.role)) {
    return res.status(403).json({ error: 'Access denied: user account required' });
  }
  next();
}

function requireAdmin(req, res, next) {
  // In single-user mode the auto-attached user is never admin,
  // so admin routes naturally stay protected by session.
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Access denied: admin account required' });
  }
  next();
}

module.exports = { requireAuth, requireUser, requireAdmin };
