from flask import Blueprint, render_template, request, redirect, url_for, flash
from modules.core.security import requires_admin_auth

from .service import (
    signup_user,
    list_users as svc_list_users,
    create_user,
    update_user,
    delete_user as svc_delete_user,
    get_user_by_token,
    set_password_service
)

from .token_service import generate_token, expiration, is_expired
from .email_service import send_user_created_email
from config_loader import load_config

users_bp = Blueprint(
    "users",
    __name__,
    template_folder="../../templates/users"
)

config = load_config()


# =========================
# LIST USERS (Oracle)
# =========================
@users_bp.route("/")
@requires_admin_auth
def list_users():
    users = svc_list_users()
    return render_template("list.html", users=users)


# =========================
# PUBLIC SIGNUP (Oracle)
# =========================
@users_bp.route("/signup", methods=["GET", "POST"])
def signup():

    if request.method == "POST":
        email = request.form.get("email", "").strip()
        name = request.form.get("name", "").strip()

        try:
            link = signup_user(email=email, name=name)
        except Exception as e:
            flash(str(e), "danger")
            return render_template("users/signup.html")

        if link and config.dev_mode == 1:
            flash(f"DEV MODE: password link → {link}", "success")
        else:
            flash("User created and email sent", "success")

        return redirect(url_for("users.signup"))

    return render_template("users/signup.html")


# =========================
# CREATE USER (Oracle)
# =========================
@users_bp.route("/new", methods=["GET", "POST"])
@requires_admin_auth
def new_user():

    if request.method == "POST":

        token = generate_token()

        create_user(
            name=request.form["name"],
            email=request.form["email"],
            role=request.form["role"],
            active="active" in request.form,
            token=token
        )

        link = url_for("users.set_password", token=token, _external=True)

        dev_link = send_user_created_email(
            request.form["email"],
            link,
            request.form["name"]
        )

        flash("User created and email sent", "success")
        return redirect(url_for("users.list_users"))

    return render_template("form.html", user=None)


# =========================
# EDIT USER (Oracle)
# =========================
@users_bp.route("/edit/<int:user_id>", methods=["GET", "POST"])
@requires_admin_auth
def edit_user(user_id):

    if request.method == "POST":
        update_user(
            user_id=user_id,
            name=request.form["name"],
            email=request.form["email"],
            role=request.form["role"],
            active="active" in request.form
        )

        return redirect(url_for("users.list_users"))

    # busca lista inteira e filtra (simples e funciona bem)
    users = svc_list_users()
    user = next((u for u in users if u["id"] == user_id), None)

    return render_template("form.html", user=user)


# =========================
# DELETE USER (Oracle)
# =========================
@users_bp.route("/delete/<int:user_id>")
@requires_admin_auth
def delete_user(user_id):

    svc_delete_user(user_id)
    return redirect(url_for("users.list_users"))


# =========================
# SET PASSWORD (Oracle)
# =========================
@users_bp.route("/set-password/<token>", methods=["GET", "POST"])
def set_password(token):

    user = get_user_by_token(token)

    if not user or is_expired(user["expire"]):
        return render_template("set_password.html", expired=True)

    if request.method == "POST":

        pwd = request.form["password"]
        pwd2 = request.form["password2"]

        if pwd != pwd2:
            flash("Passwords do not match")
            return render_template("set_password.html", expired=False)

        set_password_service(user["id"], pwd)

        flash("Password updated successfully")
        return redirect("/")

    return render_template("set_password.html", expired=False)