"""Tests for receipt and chain verification."""

from __future__ import annotations

import base64

import httpx
import pytest
import respx
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

from mailio_receipt import create_event, create_receipt
from mailio_receipt.models import Actors, Intent, IntentKind
from mailio_receipt.verification import query_backend_public_keys

DID_SIGNER = "did:web:mio.mailio.io:0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7#master"
DID_DOC_URL = "https://mio.mailio.io/0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7/did.json"
EXPECTED_PUBLIC_KEY_X = "PcrowBY5Ynz8P0tO0gq58Qa7AyzHMd9cx6TlKzQuq7s"

DID_DOCUMENT = {
    "@context": [
        "https://www.w3.org/ns/did/v1",
        "https://w3id.org/security/suites/ed25519-2020/v1",
        "https://w3id.org/security/suites/x25519-2019/v1",
    ],
    "id": "did:mailio:0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7",
    "authentication": [
        "did:mailio:0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7#master"
    ],
    "verificationMethod": [
        {
            "id": "did:mailio:0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7#master",
            "type": "JsonWebKey2020",
            "controller": "did:mailio:0xc3b00d0d230ac27855db6c0ff2d66d32bccf7ac7",
            "publicKeyJwk": {
                "crv": "Ed25519",
                "kty": "OKP",
                "x": EXPECTED_PUBLIC_KEY_X,
            },
        }
    ],
}


class TestQueryBackendPublicKeys:
    @pytest.mark.asyncio
    @respx.mock
    async def test_query_did_key_returns_correct_ed25519_public_key(self) -> None:
        """Build a receipt signed by a DID signer and verify query_backend_public_keys
        resolves the correct Ed25519 public key."""
        respx.get(DID_DOC_URL).mock(return_value=httpx.Response(200, json=DID_DOCUMENT))

        private_key = Ed25519PrivateKey.generate()
        event = create_event(
            flow_id="c03f0ebc-a387-42c8-8057-3af58801b794",
            actors=Actors(issuer=DID_SIGNER, subject=DID_SIGNER),
            intent=Intent(
                kind=IntentKind.ACTION_PLANNED,
                action="test.action",
                category="test",
            ),
        )
        receipt = create_receipt(
            event=event,
            private_key=private_key,
            signer_did=DID_SIGNER,
            role="agent",
        )

        result = await query_backend_public_keys(receipt)

        assert DID_SIGNER in result
        public_key = result[DID_SIGNER]
        assert isinstance(public_key, Ed25519PublicKey)

        raw_bytes = public_key.public_bytes_raw()
        x_b64 = base64.urlsafe_b64encode(raw_bytes).rstrip(b"=").decode()
        assert x_b64 == EXPECTED_PUBLIC_KEY_X
