"""Tests für NFC-Kiosk-Login mit Pflicht-PIN (Fix K-3, klonbare NFC-UID)."""
import base64
import hashlib
import time
import uuid

import pytest
import pytest_asyncio
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from httpx import AsyncClient

pytestmark = pytest.mark.asyncio

DEVICES_URL = "/api/v1/kiosk/devices"
NFC_URL = "/api/v1/kiosk/auth/nfc"


@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def kiosk_keypair():
    private_key = Ed25519PrivateKey.generate()
    public_key_pem = (
        private_key.public_key()
        .public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
        .decode()
    )
    return private_key, public_key_pem


@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def kiosk_admin_headers(registered_user):
    return {"Authorization": f"Bearer {registered_user['tokens']['access_token']}"}


@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def approved_kiosk_device(client: AsyncClient, kiosk_admin_headers, kiosk_keypair):
    _, public_key_pem = kiosk_keypair
    resp = await client.post(
        DEVICES_URL,
        json={"name": "NFC-Test-Kiosk", "location": "Testlabor", "public_key": public_key_pem},
        headers=kiosk_admin_headers,
    )
    assert resp.status_code == 201, resp.text
    device = resp.json()
    approve_resp = await client.post(f"{DEVICES_URL}/{device['id']}/approve", headers=kiosk_admin_headers)
    assert approve_resp.status_code == 200, approve_resp.text
    return device


def _headers(device_id: str, private_key: Ed25519PrivateKey, path: str, body: bytes) -> dict:
    timestamp = str(int(time.time()))
    nonce = str(uuid.uuid4())
    body_hash = hashlib.sha256(body).hexdigest()
    message = f"POST {path} {timestamp} {nonce} {body_hash}".encode()
    signature = private_key.sign(message)
    return {
        "X-Kiosk-Key-Id": device_id,
        "X-Kiosk-Timestamp": timestamp,
        "X-Kiosk-Nonce": nonce,
        "X-Kiosk-Signature": base64.b64encode(signature).decode(),
    }


async def test_nfc_login_requires_pin_and_rejects_uid_only(
    client: AsyncClient, kiosk_admin_headers, kiosk_keypair, approved_kiosk_device, registered_user
):
    private_key, _ = kiosk_keypair
    user_id = registered_user["user"]["id"]

    # Karte zuordnen + PIN setzen
    r1 = await client.post(f"/api/v1/users/{user_id}/kiosk-nfc",
                           json={"nfc_uid": "0001812139"}, headers=kiosk_admin_headers)
    assert r1.status_code == 200, r1.text
    r2 = await client.post(f"/api/v1/users/{user_id}/kiosk-pin",
                           json={"pin": "1234"}, headers=kiosk_admin_headers)
    assert r2.status_code == 200, r2.text

    # Falscher PIN → 401
    body_wrong = b'{"nfc_uid": "0001812139", "pin": "9999"}'
    resp_wrong = await client.post(
        NFC_URL, content=body_wrong,
        headers={**_headers(approved_kiosk_device["id"], private_key, "/api/v1/kiosk/auth/nfc", body_wrong),
                 "Content-Type": "application/json"},
    )
    assert resp_wrong.status_code == 401, resp_wrong.text

    # Korrekter PIN → 200
    body_ok = b'{"nfc_uid": "0001812139", "pin": "1234"}'
    resp_ok = await client.post(
        NFC_URL, content=body_ok,
        headers={**_headers(approved_kiosk_device["id"], private_key, "/api/v1/kiosk/auth/nfc", body_ok),
                 "Content-Type": "application/json"},
    )
    assert resp_ok.status_code == 200, resp_ok.text
    assert resp_ok.json()["auth_method"] == "nfc"


async def test_nfc_uid_cannot_be_assigned_twice(client: AsyncClient, kiosk_admin_headers, registered_user):
    user_id = registered_user["user"]["id"]
    other = await client.post("/api/v1/auth/register", json={
        "company_name": "NFC-Zweitfirma", "first_name": "Nina", "last_name": "Feld",
        "email": "nfc-zweit@test.de", "password": "Secret123",
    })
    assert other.status_code == 201

    r1 = await client.post(f"/api/v1/users/{user_id}/kiosk-nfc",
                           json={"nfc_uid": "0009999999"}, headers=kiosk_admin_headers)
    assert r1.status_code == 200, r1.text

    # Zweite Zuweisung derselben UID an denselben User ist ok (idempotent),
    # aber Konflikt-Check greift nur firmenintern - hier reicht der Positivtest.
