from flask import Blueprint, render_template, redirect, url_for, request, flash, current_app
from flask_login import login_user, logout_user, login_required, current_user
from app.extensions import db
from app.models.user import User
from app.models.company import Company
from app.models.settings import Settings

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        if current_user.is_superadmin():
            return redirect(url_for('superadmin.dashboard'))
        return redirect(url_for('admin.dashboard'))
    if request.method == 'POST':
        email = request.form.get('email', '').strip()
        password = request.form.get('password', '')
        user = User.query.filter_by(email=email).first()
        if user and user.check_password(password) and user.aktiv:
            company = Company.query.get(user.company_id)
            if (user.is_superadmin() or (company and company.aktiv)):
                login_user(user)
                user.letzter_login = __import__('datetime').datetime.utcnow()
                db.session.commit()
                if user.is_superadmin():
                    return redirect(url_for('superadmin.dashboard'))
                return redirect(url_for('admin.dashboard'))
        flash('Ungültige Anmeldedaten oder Konto deaktiviert.', 'danger')
    reg_enabled = Settings.get('registration_enabled', 'false') == 'true'
    return render_template('auth/login.html', registration_enabled=reg_enabled)

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if Settings.get('registration_enabled', 'false') != 'true':
        flash('Registrierung ist derzeit deaktiviert.', 'warning')
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        firmenname = request.form.get('firmenname', '').strip()
        email = request.form.get('email', '').strip()
        password = request.form.get('password', '')
        vorname = request.form.get('vorname', '').strip()
        nachname = request.form.get('nachname', '').strip()

        if not firmenname or not email or not password:
            flash('Bitte alle Pflichtfelder ausfüllen.', 'danger')
            return render_template('auth/register.html')

        if User.query.filter_by(email=email).first():
            flash('E-Mail bereits registriert.', 'danger')
            return render_template('auth/register.html')

        slug = firmenname.lower().replace(' ', '-').replace('ä', 'ae').replace('ö', 'oe').replace('ü', 'ue')[:100]
        base_slug = slug
        counter = 1
        while Company.query.filter_by(slug=slug).first():
            slug = f"{base_slug}-{counter}"
            counter += 1

        company = Company(name=firmenname, slug=slug)
        db.session.add(company)
        db.session.flush()

        user = User(
            company_id=company.id,
            email=email,
            vorname=vorname,
            nachname=nachname,
            rolle='firmadmin',
            darf_projekte_anlegen=True,
            darf_lv_verwalten=True,
            darf_preise_sehen=True,
            darf_aufmass_verwalten=True,
        )
        user.set_password(password)
        db.session.add(user)
        db.session.commit()

        flash('Registrierung erfolgreich! Sie können sich jetzt anmelden.', 'success')
        return redirect(url_for('auth.login'))

    return render_template('auth/register.html')

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