from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from flask import flash,redirect,url_for
from functools import wraps
from flask import session

class LoginAuth:
    def __init__(self):
        self.bp = Blueprint("auth", __name__)

        # LOGIN ROUTE
        @self.bp.route('/login', methods=['GET', 'POST'])
        def login():
            if request.method == 'POST':
                username = request.form.get("username")
                password = request.form.get("password")

                # Dummy validation — REPLACE with DB check later
                if username == "admin" and password == "admin123":
                    session['user'] = username
                    flash("Login successful!", "success")
                    return redirect(url_for('welcome'))
                else:
                    flash("Invalid username or password!", "danger")

            return render_template("login.html")

        # LOGOUT ROUTE
        @self.bp.route('/logout')
        def logout():
            session.clear()
            flash("Logged out successfully!", "success")
            return redirect(url_for('auth.login'))
        
        # ===================================================
    #       LOGIN REQUIRED DECORATOR INSIDE CLASS
    # ===================================================
    def login_required(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            if "user" not in session:
                flash("Please login first!", "danger")
                return redirect(url_for("auth.login"))
            return f(*args, **kwargs)
        return wrapper
