from uuid import uuid4

from app_new.extensions import db
from app_new.core.models.equipment import EquipmentCategory
from app_new.core.models.maintenance import Lot


def test_quick_lot_is_created_in_selected_category(authenticated_client, app):
    with app.app_context():
        category = EquipmentCategory(name=f'Catégorie rapide {uuid4().hex[:6]}')
        db.session.add(category)
        db.session.commit()
        category_id = category.id
        response = authenticated_client.post('/wizard/api/lots', json={
            'name': 'Lot créé pendant l’inventaire',
            'category_id': category_id,
        })
    assert response.status_code == 201
    payload = response.get_json()['lot']
    assert payload['category_id'] == category_id
    with app.app_context():
        lot = db.session.get(Lot, payload['id'])
        assert lot.category_id == category_id
        assert lot.is_present is True


def test_quick_lot_duplicate_returns_existing_lot(authenticated_client, app):
    with app.app_context():
        category = EquipmentCategory(name=f'Catégorie doublon {uuid4().hex[:6]}')
        lot = Lot(name='Lot identique', category=category)
        db.session.add_all([category, lot])
        db.session.commit()
        response = authenticated_client.post('/wizard/api/lots', json={
            'name': 'lot IDENTIQUE', 'category_id': category.id,
        })
        lot_id = lot.id
    assert response.status_code == 409
    assert response.get_json()['lot']['id'] == lot_id


def test_equipment_forms_offer_category_bound_lot_creation(authenticated_client):
    wizard = authenticated_client.get('/wizard/equipments')
    advanced = authenticated_client.get('/equipments/create?advanced=1')
    assert wizard.status_code == 200
    assert advanced.status_code == 200
    assert 'Nouveau lot dans cette catégorie'.encode() in wizard.data
    assert 'Créer un lot dans cette catégorie'.encode() in advanced.data
