import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change';
export function requireAuth(req, res, next) {
    const header = req.headers.authorization || '';
    let token = header.startsWith('Bearer ') ? header.slice(7) : null;
    // Allow token via query param for SSE EventSource
    if (!token && typeof req.query?.token === 'string')
        token = String(req.query.token);
    if (!token)
        return res.status(401).json({ error: 'Missing token' });
    try {
        const payload = jwt.verify(token, JWT_SECRET);
        req.user = { uid: payload.uid };
        next();
    }
    catch {
        return res.status(401).json({ error: 'Invalid token' });
    }
}
