from flask import Blueprint, render_template, request, redirect, url_for, session, flash
from app.extensions import limiter
from config import Config

config = Config()

maintenance = Blueprint("maintenance", __name__, template_folder="pages")

@maintenance.route("/maintenance", methods=["GET"])
@limiter.exempt
def maintenance_page():
    if not config.MAINTENANCE_MODE:
        return redirect("/")
    
    if session.get("maintenance_authorized") == True:
        return redirect("/")
    
    return render_template("maintenance/maintenance.html")

@maintenance.route("/maintenance", methods=["POST"])
@limiter.limit("5/minute")
def handle_maintenance_post():
    if not config.MAINTENANCE_MODE:
        return redirect("/")
        
    password = request.form.get("password")
    if password == config.MAINTENANCE_PASSWORD:
        session["maintenance_authorized"] = True
        return redirect("/")
    else:
        flash("Incorrect maintenance password", "error")
        return redirect(url_for("maintenance.maintenance_page"))
