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

from app.extensions.db import db
from app.extensions.audit_logger import AuditLogger
from app.services.auth_service import authenticate_user, parse_ldap_user
from app.models import 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)
            return render_template("login.html")

        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"))

    return render_template("login.html")


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