/**
 * Authentication middleware.
 *
 * requireApiToken  - checks Bearer token in Authorization header (for external API clients)
 * requireSession   - checks express-session (for web UI)
 * requireAny       - accepts either (allows web UI and API clients to use same routes)
 */

const { getTokenByValue } = require('../db');

function requireApiToken(req, res, next) {
  const authHeader = req.headers.authorization || '';
  const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : null;

  if (!token) {
    return res.status(401).json({ error: 'Missing Authorization header' });
  }

  const record = getTokenByValue(token);
  if (!record) {
    return res.status(401).json({ error: 'Invalid or inactive API token' });
  }

  req.apiToken = record;
  next();
}

function requireSession(req, res, next) {
  if (req.session?.admin) return next();
  return res.status(401).json({ error: 'Not authenticated' });
}

function requireAny(req, res, next) {
  // Check session first
  if (req.session?.admin) return next();

  // Then check Bearer token
  const authHeader = req.headers.authorization || '';
  const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : null;
  if (token) {
    const record = getTokenByValue(token);
    if (record) {
      req.apiToken = record;
      return next();
    }
  }

  return res.status(401).json({ error: 'Authentication required' });
}

module.exports = { requireApiToken, requireSession, requireAny };
