from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, session
from modules.users.service import signup_user
from config_loader import load_config
from modules.users.service import create_user, authenticate_user

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

config = load_config()

@auth_bp.route("/signup", methods=["GET", "POST"])
def signup():

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

        try:
            link = signup_user(email, name)

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

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

    return render_template("users/signup.html")

@auth_bp.route("/register", methods=["POST"])
def register():
    data = request.json
    create_user(data["username"], data["password"])
    return jsonify({"status": "ok"})

@auth_bp.route("/login", methods=["POST"])
def login():

    email = request.form.get("username")
    password = request.form.get("password")

    ok = authenticate_user(email, password)

    if not ok:
        flash("Invalid credentials")
        return redirect("/login")

    session["user_email"] = email

    return redirect("/")

@auth_bp.route("/login", methods=["GET"])
def login_page():
    return render_template("users/login.html")

@auth_bp.route("/logout")
def logout():
    session.clear()   # remove tudo da sessão
    return redirect("/login")
