"""Routes bâtiments et zones - GMAO Collège"""
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify
from flask_login import login_required

from app_new.extensions import db
from app_new.core.models.college import Site, Building, Zone, Room

buildings_bp = Blueprint('buildings', __name__, template_folder='templates')


@buildings_bp.route('/')
@login_required
def index():
    """Liste des bâtiments."""
    buildings = Building.query.order_by(Building.name).all()
    return render_template('equipments/buildings.html', buildings=buildings, sites=Site.query.order_by(Site.name).all())


@buildings_bp.route('/sites', methods=['POST'])
@login_required
def create_site():
    name = (request.form.get('name') or '').strip()
    if not name:
        flash('Le nom du site est obligatoire.', 'danger')
    elif Site.query.filter_by(name=name).first():
        flash('Ce site existe déjà.', 'warning')
    else:
        db.session.add(Site(name=name, site_type=request.form.get('site_type', 'college'), address=(request.form.get('address') or '').strip() or None))
        db.session.commit()
        flash(f"Site '{name}' créé.", 'success')
    return redirect(url_for('buildings.index'))


@buildings_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    """Créer un bâtiment."""
    if request.method == 'POST':
        name = (request.form.get('name') or '').strip()
        description = (request.form.get('description') or '').strip()
        if not name:
            flash('Le nom du bâtiment est requis.', 'danger')
            return render_template('equipments/building_form.html', title='Nouveau bâtiment', sites=Site.query.order_by(Site.name).all()), 400
        building = Building(name=name, description=description, site_id=request.form.get('site_id', type=int))
        db.session.add(building)
        db.session.commit()
        flash(f"Bâtiment '{building.name}' créé.", 'success')
        return redirect(url_for('buildings.index'), code=303)

    return render_template('equipments/building_form.html', title='Nouveau bâtiment', sites=Site.query.order_by(Site.name).all())


@buildings_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    """Modifier un bâtiment."""
    building = Building.query.get_or_404(id)

    if request.method == 'POST':
        name = (request.form.get('name') or '').strip()
        description = (request.form.get('description') or '').strip()
        if not name:
            flash('Le nom du bâtiment est requis.', 'danger')
            zones = Zone.query.filter_by(building_id=id).order_by(Zone.name).all()
            return render_template('equipments/building_form.html',
                                  title='Modifier le bâtiment',
                                  building=building,
                                  zones=zones, sites=Site.query.order_by(Site.name).all()), 400
        building.name = name
        building.description = description
        building.site_id = request.form.get('site_id', type=int)
        db.session.commit()
        flash(f"Bâtiment '{building.name}' mis à jour.", 'success')
        return redirect(url_for('buildings.index'), code=303)

    zones = Zone.query.filter_by(building_id=id).order_by(Zone.name).all()
    return render_template('equipments/building_form.html',
                          title='Modifier le bâtiment',
                          building=building,
                          zones=zones, sites=Site.query.order_by(Site.name).all())


@buildings_bp.route('/<int:id>/zones', methods=['POST'])
@login_required
def add_zone(id):
    """Ajouter une zone à un bâtiment."""
    building = Building.query.get_or_404(id)
    
    # Accepter a la fois JSON (API/AJAX) et formulaire classique
    if request.is_json:
        data = request.get_json() or {}
        name = data.get('name', '').strip()
    else:
        name = request.form.get('name', '').strip()
    
    if not name:
        if request.is_json:
            return jsonify({'success': False, 'error': 'Nom requis'}), 400
        flash('Nom de zone requis.', 'danger')
        return redirect(url_for('buildings.edit', id=id), code=303)
    
    zone = Zone(name=name, building_id=building.id)
    db.session.add(zone)
    db.session.commit()
    
    if request.is_json:
        return jsonify({'success': True, 'zone': {'id': zone.id, 'name': zone.name}})
    flash(f"Zone '{zone.name}' ajoutée au bâtiment.", 'success')
    return redirect(url_for('buildings.edit', id=id), code=303)
