"""Shared auth utilities — centralized login_required decorator."""
from functools import wraps

from flask import g, request, session, redirect, url_for


def login_required(f):
    """Decorator that requires the user to be logged in.

    Shared across all blueprints. Import from app.auth_utils instead
    of defining locally. For JSON API endpoints, returns 401.
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        if "user_id" not in session:
            # API endpoints expect JSON 401
            if request.content_type and "application/json" in request.content_type:
                return {"error": "Authentication required"}, 401
            return redirect(url_for("auth.login", next=request.url))
        g.user_id = session["user_id"]
        return f(*args, **kwargs)
    return decorated
