from datetime import date
from uuid import uuid4
from flask_login import login_user
from app_new.extensions import db
from app_new.core.models.prevention import PreventionAction, PreventionWorkLog, RiskAssessment
from app_new.core.models.user import User
from app_new.prevention.routes import add_risk, add_time, index


def test_prevention_dashboard_tracks_time_and_duerp(app):
    with app.app_context():
        user = User(username=f"prev-{uuid4().hex}", full_name="Prévention", role="assistant_prevention", password_hash="x")
        db.session.add(user); db.session.commit()
        with app.test_request_context(method="POST", data={"work_date": date.today().isoformat(), "duration_minutes": "90", "activity": "Visite sécurité"}):
            login_user(user); assert add_time.__wrapped__().status_code == 302
        with app.test_request_context(method="POST", data={"work_unit": "Entretien", "hazard": "Chute", "severity": "4", "probability": "3"}):
            login_user(user); assert add_risk.__wrapped__().status_code == 302
        assert PreventionWorkLog.query.filter_by(user_id=user.id).one().duration_minutes == 90
        assert RiskAssessment.query.filter_by(work_unit="Entretien").one().score == 12
        with app.test_request_context():
            login_user(user); html = index.__wrapped__()
        assert "Objectif 10 %" in html and "Visite sécurité" in html


def test_prevention_action_can_reference_a_risk(app):
    with app.app_context():
        risk = RiskAssessment(work_unit="Cuisine", hazard="Brûlure", severity=3, probability=2)
        db.session.add(risk); db.session.flush()
        action = PreventionAction(title="Installer une protection", risk=risk, owner="Gestionnaire")
        db.session.add(action); db.session.commit()
        assert action.risk.score == 6
