from __future__ import annotations

import json
from pathlib import Path

from device_gateway.auth import DeviceCredentialStore


def test_first_device_binding_and_exact_match(tmp_path: Path) -> None:
    path = tmp_path / "device.json"
    path.write_text(
        json.dumps({"device_id": "", "device_token": "secret-device-token", "pi_token": "pi-token"}),
        encoding="utf-8",
    )
    store = DeviceCredentialStore(path)
    assert store.authenticate("device-1", "secret-device-token") is True
    assert store.authenticate("device-1", "secret-device-token") is True
    assert store.authenticate("device-2", "secret-device-token") is False
    assert store.authenticate("device-1", "wrong") is False
    assert json.loads(path.read_text(encoding="utf-8"))["device_id"] == "device-1"


def test_pi_integration_has_separate_token(tmp_path: Path) -> None:
    path = tmp_path / "device.json"
    path.write_text(
        json.dumps({"device_id": "device-1", "device_token": "device", "pi_token": "pi"}),
        encoding="utf-8",
    )
    store = DeviceCredentialStore(path)
    assert store.authenticate_pi("pi") is True
    assert store.authenticate_pi("device") is False
