"""登录、登出、验证码、Token 刷新等接口单元测试。"""

import pytest
from rest_framework import status

from tests.assertions import assert_unauthorized

pytestmark = [pytest.mark.django_db]


def test_captcha_get_200(api_client):
    """GET /base/api/system/captcha/ 返回 200 与 key、image_base（需 DB 可用）。"""
    response = api_client.get("/base/api/system/captcha/")
    assert response.status_code == status.HTTP_200_OK
    data = response.json()
    assert data.get("code") == 2000, data
    assert "data" in data
    assert "key" in data["data"]
    assert "image_base" in data["data"]


def test_login_post_empty_400(api_client):
    """POST login 无 body 或缺少字段返回 400。"""
    response = api_client.post("/base/api/system/login/", {}, format="json")
    assert response.status_code in (status.HTTP_400_BAD_REQUEST, status.HTTP_401_UNAUTHORIZED)


def test_login_post_invalid_credentials_401(api_client):
    """POST login 错误账号密码返回 401/400。"""
    response = api_client.post(
        "/base/api/system/login/",
        {"username": "nonexistent", "password": "wrong"},
        format="json",
    )
    assert response.status_code in (status.HTTP_400_BAD_REQUEST, status.HTTP_401_UNAUTHORIZED)


def test_login_post_success_200(api_client, test_user):
    """POST login 正确账号密码返回 200 与 access/refresh。"""
    response = api_client.post(
        "/base/api/system/login/",
        {"username": test_user.username, "password": "TestPassword123"},
        format="json",
    )
    if response.status_code == 200:
        data = response.json()
        assert data.get("code") == 2000
        assert "data" in data and "access" in data["data"]


def test_logout_post_requires_auth(api_client):
    """POST logout 未认证返回 401 或 200+错误码。"""
    response = api_client.post("/base/api/system/logout/", {}, format="json")
    assert_unauthorized(response)


def test_logout_post_ok(authenticated_client):
    """POST logout 已认证返回 200。"""
    response = authenticated_client.post("/base/api/system/logout/", {}, format="json")
    assert response.status_code == status.HTTP_200_OK


def test_token_refresh_post_empty_400(api_client):
    """POST token/refresh/ 无 refresh 返回 400。"""
    response = api_client.post("/base/api/system/token/refresh/", {}, format="json")
    assert response.status_code in (status.HTTP_400_BAD_REQUEST, status.HTTP_401_UNAUTHORIZED)


def test_init_dictionary_get_200(api_client):
    """GET init/dictionary/ 可访问。"""
    response = api_client.get("/base/api/system/init/dictionary/")
    assert response.status_code == status.HTTP_200_OK


def test_init_settings_get_200(api_client):
    """GET init/settings/ 可访问。"""
    response = api_client.get("/base/api/system/init/settings/")
    assert response.status_code == status.HTTP_200_OK
