"""Corrections de l'audit de sécurité : Basic auth, essais répétés (django-axes), HTML nettoyé."""

import base64

from rest_framework.test import APIClient

from apps.blog.models import Post
from apps.common.html import clean_html

from .conftest import PASSWORD

LOGIN = "/api/v1/backoffice/auth/login/"


def basic(username: str, password: str) -> dict:
    token = base64.b64encode(f"{username}:{password}".encode()).decode()
    return {"HTTP_AUTHORIZATION": f"Basic {token}"}


def test_basic_auth_is_ignored_on_public_routes(api, staff):
    """Avant : 403 si mauvais mot de passe, 200 sinon, sans limite d'essais."""
    for password in ("faux", PASSWORD):
        assert api.get("/api/v1/version/", **basic("equipe", password)).status_code == 200


def test_basic_auth_gives_no_access_to_the_dashboard(api, staff):
    response = api.get("/api/v1/backoffice/messages/", **basic("equipe", PASSWORD))
    assert response.status_code == 403


def test_dashboard_login_is_locked_after_five_failures(staff):
    client = APIClient()
    for _ in range(4):
        assert client.post(LOGIN, {"username": "equipe", "password": "faux"}).status_code == 400
    # Le 5e échec déclenche le blocage, en JSON lisible par la page de connexion.
    response = client.post(LOGIN, {"username": "equipe", "password": "faux"})
    assert response.status_code == 429
    assert "Access-Control-Allow-Origin" not in response
    # Même le bon mot de passe est refusé pendant le blocage.
    response = client.post(LOGIN, {"username": "equipe", "password": PASSWORD})
    assert response.status_code == 429
    assert "Trop de tentatives" in response.json()["detail"]


def test_lockout_only_targets_the_attacker_address(staff):
    attacker = APIClient(REMOTE_ADDR="203.0.113.9")
    for _ in range(6):
        attacker.post(LOGIN, {"username": "equipe", "password": "faux"})
    team = APIClient(REMOTE_ADDR="198.51.100.4")
    assert team.post(LOGIN, {"username": "equipe", "password": PASSWORD}).status_code == 200


def test_success_resets_the_failure_count(staff):
    client = APIClient()
    for _ in range(4):
        client.post(LOGIN, {"username": "equipe", "password": "faux"})
    assert client.post(LOGIN, {"username": "equipe", "password": PASSWORD}).status_code == 200
    for _ in range(4):
        client.post(LOGIN, {"username": "equipe", "password": "faux"})
    assert client.post(LOGIN, {"username": "equipe", "password": PASSWORD}).status_code == 200


def test_django_admin_login_is_locked_too(client, staff):
    data = {"username": "equipe", "password": "faux"}
    for _ in range(5):
        client.post("/admin/login/", data)
    response = client.post("/admin/login/", {"username": "equipe", "password": PASSWORD})
    assert response.status_code == 429
    assert "Trop de tentatives" in response.content.decode()


def test_dangerous_html_is_removed():
    dirty = (
        '<p onclick="x()">Texte<script>alert(1)</script></p>'
        '<img src="x" onerror="alert(1)"><a href="javascript:alert(1)">lien</a>'
        '<iframe src="https://exemple.cm"></iframe><h2 style="color:red">Titre</h2>'
    )
    assert clean_html(dirty) == (
        '<p>Texte</p><img src="x"><a rel="noopener noreferrer">lien</a><h2>Titre</h2>'
    )


def test_editor_html_is_kept():
    html = (
        "<h2>Titre</h2><p><strong>Gras</strong> et <em>italique</em></p>"
        "<ul><li>Un</li></ul><blockquote>Citation</blockquote>"
        '<div class="content-logos"><img src="/images/a.jpg" alt="" loading="lazy"></div>'
    )
    assert clean_html(html) == html


def test_html_is_cleaned_on_save(db):
    post = Post.objects.create(
        title="Test", slug="test", excerpt="", content='<p>Ok</p><script>alert("x")</script>'
    )
    post.refresh_from_db()
    assert post.content == "<p>Ok</p>"
