from app_new.extensions import db
from app_new.core.models.equipment import Equipment, EquipmentCategory
from app_new.core.models.maintenance import Lot
from app_new.equipments.main import individualize


def test_group_unit_can_be_individualized_without_changing_total(app):
    with app.app_context():
        category = EquipmentCategory(name="Luminaires")
        lot = Lot(name="Electricite")
        group = Equipment(
            name="Luminaires A01",
            is_group=True,
            quantity=10,
            category=category,
            lot=lot,
            status="en_service",
        )
        db.session.add_all([category, lot, group])
        db.session.commit()
        group_id = group.id
        lot_id = lot.id
        category_id = category.id
        with app.test_request_context(
            f"/equipments/{group_id}/individualize",
            method="POST",
            data={
                "name": "Luminaire du milieu",
                "code": "A01-LUM-01",
                "position": "milieu, cote fenetres",
            },
        ):
            response = individualize.__wrapped__(group_id)
        assert response.status_code == 302

        group = db.session.get(Equipment, group_id)
        individual = Equipment.query.filter_by(parent_id=group_id).one()
        assert group.quantity == 10
        assert group.individualized_quantity == 1
        assert group.unindividualized_quantity == 9
        assert individual.quantity == 1
        assert individual.individual_number == 1
        assert individual.position == "milieu, cote fenetres"
        assert individual.lot_id is None
        assert individual.category_id is None
        assert individual.effective_lot_id == lot_id
        assert individual.effective_category_id == category_id


def test_group_cannot_individualize_more_than_declared_quantity(app):
    with app.app_context():
        group = Equipment(name="Luminaire unique", is_group=True, quantity=1)
        db.session.add(group)
        db.session.commit()
        group_id = group.id
        with app.test_request_context(method="POST"):
            assert individualize.__wrapped__(group_id).status_code == 302
        with app.test_request_context(method="POST"):
            assert individualize.__wrapped__(group_id).status_code == 302

        assert Equipment.query.filter_by(parent_id=group_id).count() == 1
