from flask import Blueprint, abort, current_app, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_user, logout_user

from app.extensions import db, login_manager
from app.models import User

bp = Blueprint("auth", __name__, url_prefix="/auth")


@login_manager.user_loader
def load_user(user_id):
    return db.session.get(User, int(user_id))


def _post_login_redirect(user):
    """Send development users to the most useful landing page for their role."""
    if user.has_role("SUPER_ADMIN", "PIRAMAL_ADMIN", "INDIAISUS_ADMIN"):
        return redirect(url_for("admin.dashboard"))
    if user.has_role("MANAGER"):
        return redirect(url_for("manager.approvals"))
    return redirect(url_for("employee.dashboard"))


@bp.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated:
        return _post_login_redirect(current_user)

    # Development-only SSO bypass. ProductionConfig forces DEV_LOGIN_ENABLED=False.
    if request.method == "POST" and current_app.config.get("DEV_LOGIN_ENABLED"):
        email = request.form.get("email", "").strip().lower()
        user = User.query.filter_by(official_email=email, is_active=True).first()
        if user:
            login_user(user)
            return _post_login_redirect(user)
        flash("User not found in development login.", "danger")

    return render_template("auth/login.html")


@bp.route("/dev-login/<account_type>")
def dev_login(account_type):
    """One-click local login for the three seeded test personas."""
    if not current_app.config.get("DEV_LOGIN_ENABLED"):
        abort(404)

    accounts = {
        "admin": "admin@sevasetu.local",
        "manager": "manager@sevasetu.local",
        "employee": "employee@sevasetu.local",
    }
    email = accounts.get(account_type.lower())
    if not email:
        abort(404)

    user = User.query.filter_by(official_email=email, is_active=True).first()
    if not user:
        flash("Development user is missing. Run: python scripts/seed.py", "danger")
        return redirect(url_for("auth.login"))

    login_user(user)
    return _post_login_redirect(user)


@bp.route("/logout")
def logout():
    logout_user()
    return redirect(url_for("auth.login"))
