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

USERS = "/api/v1/backoffice/users/"
NEW = {"username": "awa", "email": "awa@cederconsulting.com", "password": "Bonjour-Ceder-2026!"}


def test_create_staff_account(staff_api):
    response = staff_api.post(USERS, NEW, format="json")
    assert response.status_code == 201
    assert "password" not in response.json()
    user = get_user_model().objects.get(username="awa")
    assert user.is_staff and not user.is_superuser
    assert user.check_password(NEW["password"])


def test_password_required_and_validated(staff_api):
    assert staff_api.post(USERS, {**NEW, "password": ""}, format="json").status_code == 400
    response = staff_api.post(USERS, {**NEW, "password": "1234"}, format="json")
    assert "password" in response.json()


def test_list_only_staff(staff_api, staff):
    get_user_model().objects.create_user("client", password="x")
    assert [u["username"] for u in staff_api.get(USERS).json()] == ["equipe"]


def test_cannot_deactivate_self(staff_api, staff):
    response = staff_api.patch(f"{USERS}{staff.id}/", {"is_active": False}, format="json")
    assert response.status_code == 400


def test_deactivated_account_is_logged_out(staff_api):
    other = get_user_model().objects.create_user("awa", password="x", is_staff=True)
    client = APIClient()
    client.force_login(other)
    staff_api.patch(f"{USERS}{other.id}/", {"is_active": False}, format="json")
    assert client.get(USERS).status_code == 403


def test_reset_password_keeps_it_when_blank(staff_api):
    other = get_user_model().objects.create_user("awa", password="Ancien-mot-2026!", is_staff=True)
    staff_api.patch(f"{USERS}{other.id}/", {"password": "", "first_name": "Awa"}, format="json")
    other.refresh_from_db()
    assert other.check_password("Ancien-mot-2026!")
    staff_api.patch(f"{USERS}{other.id}/", {"password": "Nouveau-mot-2026!"}, format="json")
    other.refresh_from_db()
    assert other.check_password("Nouveau-mot-2026!")


def test_superuser_protected_from_staff(staff_api):
    boss = get_user_model().objects.create_superuser("boss", "b@c.com", "x")
    response = staff_api.patch(f"{USERS}{boss.id}/", {"password": "Pirate-2026!!"}, format="json")
    assert response.status_code == 403


def test_no_delete(staff_api, staff):
    assert staff_api.delete(f"{USERS}{staff.id}/").status_code == 405


def test_django_admin_reserved_to_superusers(client, staff):
    client.force_login(staff)
    assert client.get("/admin/").status_code == 302
    staff.is_superuser = True
    staff.save()
    assert client.get("/admin/").status_code == 200
