import jwt from 'jsonwebtoken';
import { sendError } from '../util/httpError.js';

export function requireAuth(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) {
    return sendError(res, 401, 'UNAUTHORIZED', 'Missing bearer token');
  }
  try {
    const secret = process.env.JWT_SECRET;
    if (!secret) {
      return sendError(res, 500, 'SERVER_CONFIG', 'JWT_SECRET is not set');
    }
    const payload = jwt.verify(token, secret);
    req.user = {
      id: Number(payload.sub),
      role: payload.role,
      phone: payload.phone,
    };
    return next();
  } catch {
    return sendError(res, 401, 'UNAUTHORIZED', 'Invalid or expired token');
  }
}

export function requireRole(...roles) {
  return (req, res, next) => {
    if (!req.user) {
      return sendError(res, 401, 'UNAUTHORIZED', 'Not authenticated');
    }
    if (!roles.includes(req.user.role)) {
      return sendError(res, 403, 'FORBIDDEN', 'Insufficient role');
    }
    return next();
  };
}

export function signUserToken(user) {
  const secret = process.env.JWT_SECRET;
  if (!secret) throw new Error('JWT_SECRET is not set');
  const expiresIn = process.env.JWT_EXPIRES_IN || '7d';
  return jwt.sign(
    { sub: String(user.id), role: user.role, phone: user.phone },
    secret,
    { expiresIn }
  );
}
