// Bearer-token auth. requireAuth blocks, optionalAuth attaches if present.
import { verifyAccessToken } from '../utils/jwt.js';
import { HttpError } from './error.js';

function readToken(req) {
  const header = req.get('authorization') || '';
  return header.startsWith('Bearer ') ? header.slice(7).trim() : null;
}

export function requireAuth(req, _res, next) {
  const token = readToken(req);
  if (!token) return next(new HttpError(401, 'unauthorized', 'Sign in required'));
  try {
    const payload = verifyAccessToken(token);
    req.auth = { userId: payload.sub, email: payload.email, role: payload.role };
    next();
  } catch {
    next(new HttpError(401, 'unauthorized', 'Session expired, please sign in again'));
  }
}

export function optionalAuth(req, _res, next) {
  const token = readToken(req);
  if (token) {
    try {
      const payload = verifyAccessToken(token);
      req.auth = { userId: payload.sub, email: payload.email, role: payload.role };
    } catch {
      // ignore a bad/expired token on optional routes
    }
  }
  next();
}

export function requireAdmin(req, _res, next) {
  if (!req.auth || req.auth.role !== 'admin') {
    return next(new HttpError(403, 'forbidden', 'Admin only'));
  }
  next();
}
