from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import login_required

from app.helpers import copropriete_required, get_by_public_id
from app.models import Lot, LotType, MilliemeType, ReleveType, db

bp = Blueprint("types", __name__, url_prefix="/parametres")


@bp.route("/")
@login_required
@copropriete_required
def index(copropriete):
    millieme_types = (
        MilliemeType.query.filter_by(copropriete_id=copropriete.id)
        .order_by(MilliemeType.ordre, MilliemeType.libelle)
        .all()
    )
    releve_types = (
        ReleveType.query.filter_by(copropriete_id=copropriete.id)
        .order_by(ReleveType.ordre, ReleveType.libelle)
        .all()
    )
    lot_types = (
        LotType.query.filter_by(copropriete_id=copropriete.id)
        .order_by(LotType.ordre, LotType.libelle)
        .all()
    )
    return render_template(
        "types/index.html",
        copropriete=copropriete,
        millieme_types=millieme_types,
        releve_types=releve_types,
        lot_types=lot_types,
    )


@bp.route("/milliemes/ajouter", methods=["POST"])
@login_required
@copropriete_required
def ajouter_millieme(copropriete):
    libelle = request.form.get("libelle", "").strip()
    if not libelle:
        flash("Le libellé est obligatoire.", "danger")
    else:
        max_ordre = (
            db.session.query(db.func.max(MilliemeType.ordre))
            .filter_by(copropriete_id=copropriete.id)
            .scalar()
            or 0
        )
        db.session.add(
            MilliemeType(copropriete_id=copropriete.id, libelle=libelle, ordre=max_ordre + 1)
        )
        db.session.commit()
        flash(f"Type de tantièmes « {libelle} » ajouté.", "success")
    return redirect(url_for("types.index"))


@bp.route("/milliemes/<uuid:type_id>/supprimer", methods=["POST"])
@login_required
@copropriete_required
def supprimer_millieme(copropriete, type_id):
    mt = get_by_public_id(
        MilliemeType, type_id, copropriete_id=copropriete.id
    )
    db.session.delete(mt)
    db.session.commit()
    flash("Type de tantièmes supprimé.", "info")
    return redirect(url_for("types.index"))


@bp.route("/releves/ajouter", methods=["POST"])
@login_required
@copropriete_required
def ajouter_releve_type(copropriete):
    libelle = request.form.get("libelle", "").strip()
    unite = request.form.get("unite", "").strip()
    if not libelle:
        flash("Le libellé est obligatoire.", "danger")
    else:
        max_ordre = (
            db.session.query(db.func.max(ReleveType.ordre))
            .filter_by(copropriete_id=copropriete.id)
            .scalar()
            or 0
        )
        db.session.add(
            ReleveType(
                copropriete_id=copropriete.id,
                libelle=libelle,
                unite=unite,
                ordre=max_ordre + 1,
            )
        )
        db.session.commit()
        flash(f"Type de relevé « {libelle} » ajouté.", "success")
    return redirect(url_for("types.index"))


@bp.route("/releves/<uuid:type_id>/supprimer", methods=["POST"])
@login_required
@copropriete_required
def supprimer_releve_type(copropriete, type_id):
    rt = get_by_public_id(
        ReleveType, type_id, copropriete_id=copropriete.id
    )
    db.session.delete(rt)
    db.session.commit()
    flash("Type de relevé supprimé.", "info")
    return redirect(url_for("types.index"))


@bp.route("/lots/ajouter", methods=["POST"])
@login_required
@copropriete_required
def ajouter_lot_type(copropriete):
    libelle = request.form.get("libelle", "").strip()
    if not libelle:
        flash("Le libellé est obligatoire.", "danger")
    else:
        max_ordre = (
            db.session.query(db.func.max(LotType.ordre))
            .filter_by(copropriete_id=copropriete.id)
            .scalar()
            or 0
        )
        db.session.add(
            LotType(copropriete_id=copropriete.id, libelle=libelle, ordre=max_ordre + 1)
        )
        db.session.commit()
        flash(f"Type de lot « {libelle} » ajouté.", "success")
    return redirect(url_for("types.index"))


@bp.route("/lots/<uuid:type_id>/supprimer", methods=["POST"])
@login_required
@copropriete_required
def supprimer_lot_type(copropriete, type_id):
    lt = get_by_public_id(LotType, type_id, copropriete_id=copropriete.id)
    Lot.query.filter_by(lot_type_id=lt.id).update({Lot.lot_type_id: None})
    db.session.delete(lt)
    db.session.commit()
    flash("Type de lot supprimé.", "info")
    return redirect(url_for("types.index"))
