from flask import Blueprint, request, session, redirect, url_for, render_template
from backend.db_core import get_connection

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    alias_ingresado = request.form.get('alias', '').strip().upper()
    pin_ingresado = request.form.get('pin_firma', '').strip()
    uuid_terminal = request.form.get('uuid_terminal', '').strip()
    nombre_equipo = request.form.get('nombre_equipo', 'Dispositivo Desconocido').strip()

    db = get_connection()
    cursor = db.cursor(dictionary=True)

    try:
        cursor.execute("SELECT * FROM utrau_usuarios WHERE alias = %s AND estado = 'ACTIVO'", (alias_ingresado,))
        user = cursor.fetchone()

        if not user or str(user['pin_firma']).strip() != pin_ingresado:
            return render_template('login.html', error="Compañero no encontrado, inactivo o PIN incorrecto.")

        if uuid_terminal:
            cursor.execute("SELECT * FROM utrau_terminales_activas WHERE uuid_terminal = %s", (uuid_terminal,))
            terminal = cursor.fetchone()

            if not terminal:
                cursor.execute("""
                    INSERT INTO utrau_terminales_activas (uuid_terminal, nombre_equipo, id_usuario_actual, estado) 
                    VALUES (%s, %s, %s, 'CONECTADO')
                """, (uuid_terminal, nombre_equipo, user['id_usuario']))
            else:
                cursor.execute("""
                    UPDATE utrau_terminales_activas 
                    SET estado = 'CONECTADO', id_usuario_actual = %s, ultima_conexion = CURRENT_TIMESTAMP 
                    WHERE uuid_terminal = %s
                """, (user['id_usuario'], uuid_terminal))

        session.clear()
        session['user_id'] = user['id_usuario']
        session['user_rol'] = user['rol']
        session['user_alias'] = user['alias']
        session['tema_visual'] = user['tema_visual']

        cursor.execute("UPDATE utrau_usuarios SET ultima_conexion = CURRENT_TIMESTAMP WHERE id_usuario = %s", (user['id_usuario'],))
        
        db.commit()
        return redirect(url_for('index'))

    except Exception as e:
        db.rollback()
        return render_template('login.html', error=f"Error interno: {str(e)}")
    finally:
        cursor.close()
        db.close()


@auth_bp.route('/toggle_theme')
def toggle_theme():
    if 'user_id' not in session:
        return redirect(url_for('auth.login'))
        
    nuevo_tema = 1 if session.get('tema_visual', 0) == 0 else 0
    
    try:
        db = get_connection()
        cursor = db.cursor()
        cursor.execute("UPDATE utrau_usuarios SET tema_visual = %s WHERE id_usuario = %s", (nuevo_tema, session['user_id']))
        db.commit()
    except Exception as e:
        pass
    finally:
        cursor.close()
        db.close()
        
    session['tema_visual'] = nuevo_tema
    return redirect(request.referrer or url_for('index'))

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