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

from app.extensions.audit_logger import AuditLogger
from app.extensions.db import db
from app.models import User
from app.services.auth_service import authenticate_user, parse_ldap_user

auditlog = AuditLogger(db.session)

auth_bp = Blueprint('auth', __name__, url_prefix='/telezab/')

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if 'user_id' in session:
        return redirect(url_for('dashboard.dashboard'))

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        success, user_info, error = authenticate_user(username, password)

        if not success:
            flash(error, 'danger')
            auditlog.auth(username_attempted=username, success=False, error=error)
            session['login_username'] = username  # сохраняем введённый логин
            return redirect(url_for('auth.login'))  # редирект вместо render_template

        # Очистка сохранённого логина при успешном входе
        session.pop('login_username', None)

        data = parse_ldap_user(user_info)
        display_name = (f"{data['user_surname']} {data['user_name']} {data['user_middle_name']}").strip()
        user = User(
            user_id=data['sam_account_name'],
            user_name=data['user_name'],
            user_surname=data['user_surname'],
            user_middle_name=data['user_middle_name'],
            display_name=display_name,
            email=data['email']
        )

        session.permanent = True
        session['username'] = data['sam_account_name']
        session['display_name'] = display_name
        session['user_data'] = data
        login_user(user)

        auditlog.auth(username_attempted=username, success=True, ldap_user_id=data['sam_account_name'], display_name=display_name)
        flash("Logged in successfully!", "success")
        return redirect(url_for("dashboard.dashboard"))

    # GET-запрос — передаём в шаблон ранее введённый логин, если есть
    username_prefill = session.pop('login_username', '')
    return render_template("login.html", username=username_prefill)



@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    session.clear()
    return redirect(url_for('auth.login'))
