from functools import wraps
from flask import redirect, session, request, jsonify

SUB_ADMIN_ALLOWED = {
    "admin.dashboard_page",
    "admin.visitors_page",
    "admin.edit_visitor",
    "admin.search_visitors_api",
    "admin.add_visitor_api",
    "admin.api_export_visitors",
    "admin.consent_page",
    "admin.api_get_consent",
    "admin.api_save_consent",
    "admin.static",
    "auth.logout",
}


def admin_login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # Check login
        logged_in = session.get("user_id") or session.get("admin_logged_in")
        if not logged_in:
            return redirect("/login")

        role = session.get("role") or session.get("admin_role") or ""

        # Admin — full access
        if role == "admin":
            return f(*args, **kwargs)

        # Sub admin — limited access
        if role == "sub_admin":
            if request.endpoint in SUB_ADMIN_ALLOWED:
                return f(*args, **kwargs)
            if request.is_json or request.path.startswith("/admin/api/"):
                return jsonify({"error": "Access denied"}), 403
            return redirect("/subadmin/dashboard")

        # Photographer — no admin access, go to upload
        if role == "photographer":
            return redirect("/upload")

        # Unknown — login
        return redirect("/login")

    return decorated_function