"""Requalification des prérequis réellement rattachés au technicien."""

from datetime import date, time

from app_new import db
from app_new.core.models.planning import AnnualTimeConfig, WorkSchedule
from app_new.core.models.user import User
from app_new.core.services.planning_service import PlanningService


def _user(username, name):
    user = User(username=username, email=f"{username}@gmao.local", full_name=name, is_active=True)
    user.set_password("phase21-requalification-password")
    db.session.add(user)
    db.session.flush()
    return user


def test_working_hours_are_isolated_between_two_technicians(app):
    with app.app_context():
        tech_a = _user("phase21_tech_a", "Technicien A")
        tech_b = _user("phase21_tech_b", "Technicien B")
        db.session.add_all([
            WorkSchedule(user_id=tech_a.id, day_of_week=0, start_time=time(8), end_time=time(17), lunch_start=time(12), lunch_end=time(13, 30)),
            WorkSchedule(user_id=tech_b.id, day_of_week=0, start_time=time(7), end_time=time(15, 30), lunch_start=time(11, 30), lunch_end=time(12, 30)),
        ])
        db.session.commit()
        try:
            monday = date(2026, 8, 24)
            assert PlanningService.get_working_hours(monday, user_id=tech_a.id)[:2] == (time(8), time(17))
            assert PlanningService.get_working_hours(monday, user_id=tech_b.id)[:2] == (time(7), time(15, 30))
        finally:
            WorkSchedule.query.filter(WorkSchedule.user_id.in_([tech_a.id, tech_b.id])).delete(synchronize_session=False)
            AnnualTimeConfig.query.filter(AnnualTimeConfig.user_id.in_([tech_a.id, tech_b.id])).delete(synchronize_session=False)
            db.session.delete(tech_a)
            db.session.delete(tech_b)
            db.session.commit()

