import factory
from app_new.core.models.user import User
from app_new import db
from app_new.core.models.rbac import Role, UserRole


class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = User
        sqlalchemy_session = db.session
        sqlalchemy_session_persistence = 'commit'

    username = factory.Sequence(lambda n: f'user_{n}')
    email = factory.LazyAttribute(lambda obj: f'{obj.username}@test.local')
    password_hash = 'pbkdf2:sha256$fakehash$fakehash'  # mot de passe factice
    full_name = factory.LazyAttribute(lambda obj: obj.username.replace('_', ' ').title())
    role = 'technicien'
    is_active = True

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        user = super()._create(model_class, *args, **kwargs)
        role = Role.query.filter_by(slug=user.role, is_active=True).first()
        if role and not UserRole.query.filter_by(user_id=user.id, role_id=role.id).first():
            db.session.add(UserRole(user_id=user.id, role_id=role.id))
            db.session.commit()
        return user


class AdminFactory(UserFactory):
    role = 'admin'
    username = factory.Sequence(lambda n: f'admin_{n}')
