"""
MCLogger – Authentifizierung
Getrennte Login-Seiten für Site-Admins und normale Nutzer/Gruppen-Admins.
"""
import json
from flask import Blueprint, render_template, request, redirect, url_for, session, flash
from panel_db import check_login, get_user_groups

auth = Blueprint("auth", __name__)


@auth.route("/login", methods=["GET", "POST"])
def login():
    if session.get("user_id"):
        return redirect(url_for("panel.dashboard"))
    error = None
    if request.method == "POST":
        user = check_login(request.form.get("username", ""), request.form.get("password", ""))
        if user and user["is_site_admin"]:
            flash("Please use the Site Admin login.", "warning")
            return redirect(url_for("auth.admin_login"))
        if user:
            groups = get_user_groups(user["id"])
            if not groups:
                error = "You are not assigned to any group. Please contact an admin."
            else:
                _set_user_session(user, groups)
                return redirect(url_for("panel.dashboard"))
        else:
            error = "Incorrect username or password."
    return render_template("auth/login.html", error=error)


@auth.route("/admin/login", methods=["GET", "POST"])
def admin_login():
    if session.get("is_site_admin"):
        return redirect(url_for("site_admin.dashboard"))
    error = None
    if request.method == "POST":
        user = check_login(request.form.get("username", ""), request.form.get("password", ""))
        if user and user["is_site_admin"]:
            session["user_id"]       = user["id"]
            session["username"]      = user["username"]
            session["is_site_admin"] = True
            session["group_id"]      = None
            session["permissions"]   = {}
            return redirect(url_for("site_admin.dashboard"))
        elif user:
            error = "No Site Admin privileges."
        else:
            error = "Incorrect username or password."
    return render_template("auth/admin_login.html", error=error)


@auth.route("/logout", methods=["POST"])
def logout():
    session.clear()
    return redirect(url_for("auth.login"))


@auth.route("/switch-group/<int:group_id>", methods=["POST"])
def switch_group(group_id):
    if not session.get("user_id") or session.get("is_site_admin"):
        return redirect(url_for("auth.login"))
    user_id = session["user_id"]
    groups  = get_user_groups(user_id)
    target  = next((g for g in groups if g["id"] == group_id), None)
    if not target:
        flash("Group not found or no access.", "danger")
        return redirect(url_for("panel.dashboard"))
    _apply_group(target)
    return redirect(url_for("panel.dashboard"))


def _set_user_session(user, groups):
    session["user_id"]       = user["id"]
    session["username"]      = user["username"]
    session["is_site_admin"] = False
    _apply_group(groups[0])  # Erste Gruppe als Standard


def _apply_group(group):
    raw = group.get("permissions")
    if isinstance(raw, str):
        perms = json.loads(raw)
    elif isinstance(raw, dict):
        perms = raw
    else:
        perms = {}
    session["group_id"]   = group["id"]
    session["group_name"] = group["name"]
    session["role"]       = group.get("role", "member")
    session["permissions"] = perms
