"""Vérifie la matrice de rôles sur de vraies routes Flask."""
from uuid import uuid4

import pytest

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


def _login_as(client, app, role):
    client.get("/auth/logout")
    password = "mot-de-passe-test-solide"
    with app.app_context():
        suffix = uuid4().hex[:8]
        user = User(
            username=f"rbac_{role}_{suffix}",
            email=f"rbac_{role}_{suffix}@test.local",
            full_name=f"Test {role}", role=role, is_active=True,
        )
        user.set_password(password)
        db.session.add(user)
        db.session.flush()
        rbac_role = Role.query.filter_by(slug=role, is_active=True).first()
        db.session.add(UserRole(user_id=user.id, role_id=rbac_role.id))
        db.session.commit()
        username = user.username
    response = client.post("/auth/login", data={"username": username, "password": password})
    assert response.status_code == 302


@pytest.mark.parametrize(
    ("legacy, canonical"),
    [
        ("super_admin", "admin"), ("chef", "responsable_gmao"),
        ("tech", "technicien"), ("user", "demandeur"), ("viewer", "lecture"),
    ],
)
def test_legacy_roles_are_normalized(legacy, canonical):
    assert canonical_role(legacy) == canonical


@pytest.mark.parametrize(
    ("role, equipment_status, admin_status"),
    [
        ("admin", 200, 200),
        ("responsable_gmao", 200, 403),
        ("technicien", 200, 403),
        ("assistant_prevention", 200, 403),
        ("demandeur", 403, 403),
        ("lecture", 200, 403),
    ],
)
def test_role_access_to_real_pages(client, app, role, equipment_status, admin_status):
    _login_as(client, app, role)
    assert client.get("/equipments/").status_code == equipment_status
    assert client.get("/admin/").status_code == admin_status


@pytest.mark.parametrize("role", ["demandeur", "lecture", "assistant_prevention"])
def test_non_maintainers_cannot_mutate_patrimony(client, app, role):
    _login_as(client, app, role)
    response = client.post("/equipments/categories/new", data={"name": "Interdit"})
    assert response.status_code == 403
