from django.contrib.auth import get_user_model
from rest_framework.test import APIClient

from .conftest import PASSWORD

ACCOUNT = "/api/v1/backoffice/account/"
PASSWORD_URL = "/api/v1/backoffice/account/password/"
ME = "/api/v1/backoffice/auth/me/"


def test_read_account(staff_api):
    assert staff_api.get(ACCOUNT).json() == {
        "username": "equipe",
        "first_name": "Awa",
        "last_name": "",
        "email": "equipe@cederconsulting.com",
    }


def test_update_account(staff_api, staff):
    data = {"username": "cederconsulting", "first_name": "Awa", "last_name": "Ngo"}
    response = staff_api.patch(ACCOUNT, data, format="json")
    assert response.json()["display_name"] == "Awa Ngo"
    staff.refresh_from_db()
    assert staff.username == "cederconsulting"


def test_username_must_be_unique(staff_api):
    get_user_model().objects.create_user("pris", "pris@example.cm", "x")
    response = staff_api.patch(ACCOUNT, {"username": "pris"}, format="json")
    assert response.status_code == 400
    assert "username" in response.json()


def test_email_is_required(staff_api):
    assert staff_api.patch(ACCOUNT, {"email": ""}, format="json").status_code == 400


def test_change_password_keeps_session(staff_api, staff):
    data = {"current_password": PASSWORD, "new_password": "Nouveau-mot-2026!"}
    assert staff_api.post(PASSWORD_URL, data, format="json").status_code == 204
    staff.refresh_from_db()
    assert staff.check_password("Nouveau-mot-2026!")
    assert staff_api.get(ME).status_code == 200


def test_change_password_checks_current_and_strength(staff_api):
    wrong = staff_api.post(
        PASSWORD_URL, {"current_password": "faux", "new_password": "Nouveau-mot-2026!"}
    )
    assert "current_password" in wrong.json()
    weak = staff_api.post(PASSWORD_URL, {"current_password": PASSWORD, "new_password": "123"})
    assert "new_password" in weak.json()


def test_reserved_to_staff(db):
    assert APIClient().get(ACCOUNT).status_code == 403
