from app_new.extensions import db
from app_new.core.models.equipment import Equipment
from app_new.core.models.maintenance import Lot
from app_new.lots.routes import index, set_presence


def test_empty_lot_is_visible_and_can_be_marked_absent(app):
    with app.app_context():
        lot = Lot(name="Ascenseurs")
        db.session.add(lot)
        db.session.commit()
        lot_id = lot.id
        with app.test_request_context('/lots/'):
            rendered = index.__wrapped__()
        assert 'Aucun équipement' in rendered

        with app.test_request_context(
            f'/lots/{lot_id}/presence',
            method='POST',
            data={'action': 'absent', 'absence_reason': 'Aucun ascenseur dans le college'},
        ):
            response = set_presence.__wrapped__(lot_id)
        assert response.status_code == 302

        lot = db.session.get(Lot, lot_id)
        assert lot.is_present is False
        assert lot.absence_reason == 'Aucun ascenseur dans le college'
        assert lot.needs_equipment_attention is False


def test_lot_with_equipment_cannot_be_marked_absent(app):
    with app.app_context():
        lot = Lot(name="Electricite")
        equipment = Equipment(
            name="Luminaires A01",
            is_group=True,
            quantity=10,
            lot=lot,
            status='en_service',
        )
        db.session.add_all([lot, equipment])
        db.session.commit()
        lot_id = lot.id
        with app.test_request_context(
            f'/lots/{lot_id}/presence',
            method='POST',
            data={'action': 'absent'},
        ):
            response = set_presence.__wrapped__(lot_id)
        assert response.status_code == 302

        assert db.session.get(Lot, lot_id).is_present is True
