"""Routes 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 Building, Zone

zones_bp = Blueprint('zones', __name__, template_folder='templates')


@zones_bp.route('/')
@login_required
def index():
    """Liste des zones."""
    zones = Zone.query.join(Building).order_by(Building.name, Zone.name).all()
    return render_template('equipments/zones.html', zones=zones)


@zones_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    """Créer une zone."""
    if request.method == 'POST':
        zone = Zone(
            name=request.form.get('name'),
            building_id=request.form.get('building_id', type=int),
            mowing_minutes=request.form.get('mowing_minutes', type=int) or None,
            edging_minutes=request.form.get('edging_minutes', type=int) or None,
            hedge_minutes=request.form.get('hedge_minutes', type=int) or None,
            branch_removal_minutes=request.form.get('branch_removal_minutes', type=int) or None,
        )
        db.session.add(zone)
        db.session.commit()
        flash(f"Zone '{zone.name}' créée.", 'success')
        return redirect(url_for('zones.index'))

    buildings = Building.query.order_by(Building.name).all()
    return render_template('equipments/zone_form.html', title='Nouvelle zone', buildings=buildings)


@zones_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    """Modifier une zone."""
    zone = Zone.query.get_or_404(id)

    if request.method == 'POST':
        zone.name = request.form.get('name')
        zone.building_id = request.form.get('building_id', type=int)
        zone.mowing_minutes = request.form.get('mowing_minutes', type=int) or None
        zone.edging_minutes = request.form.get('edging_minutes', type=int) or None
        zone.hedge_minutes = request.form.get('hedge_minutes', type=int) or None
        zone.branch_removal_minutes = request.form.get('branch_removal_minutes', type=int) or None
        db.session.commit()
        flash(f"Zone '{zone.name}' mise à jour.", 'success')
        return redirect(url_for('zones.index'))

    buildings = Building.query.order_by(Building.name).all()
    return render_template('equipments/zone_form.html',
                          title='Modifier la zone',
                          zone=zone,
                          buildings=buildings)


@zones_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    """Supprimer une zone."""
    zone = Zone.query.get_or_404(id)
    db.session.delete(zone)
    db.session.commit()
    flash(f"Zone '{zone.name}' supprimée.", 'success')
    return redirect(url_for('zones.index'))


@zones_bp.route('/<int:id>', methods=['DELETE'])
@login_required
def delete_api(id):
    """Supprimer une zone via API (DELETE)."""
    zone = Zone.query.get_or_404(id)
    db.session.delete(zone)
    db.session.commit()
    return jsonify({'success': True})
