from __future__ import annotations

from flask import Blueprint, flash, redirect, render_template, url_for
from flask_login import current_user, login_required, login_user, logout_user

from ..extensions import db
from ..forms import LoginForm, RegisterForm
from ..models import User


bp = Blueprint("auth", __name__)


def registration_open() -> bool:
    return User.query.count() == 0


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

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data.lower().strip()).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            flash(f"Willkommen zurück, {user.name}.", "success")
            return redirect(url_for("tasks.my_tasks"))
        flash("Die Kombination aus E-Mail und Passwort passt leider nicht.", "error")
    return render_template("auth/login.html", form=form, registration_open=registration_open())


@bp.route("/register", methods=["GET", "POST"])
def register():
    if current_user.is_authenticated:
        return redirect(url_for("tasks.my_tasks"))
    if not registration_open():
        flash("Freie Registrierung ist deaktiviert.", "info")
        return redirect(url_for("auth.login"))

    form = RegisterForm()
    if form.validate_on_submit():
        user = User(name=form.name.data.strip(), email=form.email.data.lower().strip())
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        flash("Dein Konto ist bereit. Willkommen in der Putzliga.", "success")
        return redirect(url_for("tasks.my_tasks"))
    return render_template("auth/register.html", form=form)


@bp.route("/logout")
@login_required
def logout():
    logout_user()
    flash("Du bist jetzt abgemeldet.", "info")
    return redirect(url_for("auth.login"))
