package license

import (
	"crypto/ed25519"
	"encoding/base64"
	"encoding/json"
	"testing"
)

const (
	protocolVectorPublicKey  = "A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg"
	queryVectorSignature     = "SIGN-TwKDMAmaHdqpbGM8QG70L-BF1evFWOzCGyFFrsMqdKW_Dx_oEERI2lojYndSIgajawo2ZprLIou4sXEkWCQOAA"
	queryVectorResponse      = `{"auth":"Yes And Must","status":"active","version":"1.0.0","updateUrl":"https://updates.example.test/qycw/1.0.0","dbUpdate":false,"updateTime":"2026-07-12T02:00:00Z","changelog":"integration-vector","forceUpdate":false,"servicePurchase":"2026-01-01T00:00:00Z","serviceExpire":"2027-01-01T00:00:00Z","purchase":"2026-01-01T00:00:00Z","expire":"2027-01-01T00:00:00Z","license":"AUTH-DEV-00000001","licenseNo":"LIC-DEV-0001","validUntil":"2026-07-12T11:00:00Z","expiresAt":"2027-01-01T00:00:00Z","nonce":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYX","issuedAt":1783831200,"keyId":"dev-key-2026-01","instanceId":"550e8400-e29b-41d4-a716-446655440000","sequence":103,"features":["http","worker","plugins"],"signature":"SIGN-TwKDMAmaHdqpbGM8QG70L-BF1evFWOzCGyFFrsMqdKW_Dx_oEERI2lojYndSIgajawo2ZprLIou4sXEkWCQOAA"}`
	heartbeatVectorSignature = "SIGN-fewr_cNYvci8o0vLV_vKwQs7isAw-bq9YUb4ATlhL1i8LRRzmPmv51-o8HFVC4VvwXf5mniswrIUx-ToxUPvAw"
	heartbeatVectorResponse  = `{"status":"active","validUntil":"2026-07-12T11:05:00Z","expiresAt":"2027-01-01T00:00:00Z","licenseNo":"LIC-DEV-0001","instanceId":"550e8400-e29b-41d4-a716-446655440000","sequence":104,"keyId":"dev-key-2026-01","features":["http","worker","plugins"],"nonce":"GBkaGxwdHh8gISIjJCUmJygpKissLS4v","issuedAt":1783831500,"signature":"SIGN-fewr_cNYvci8o0vLV_vKwQs7isAw-bq9YUb4ATlhL1i8LRRzmPmv51-o8HFVC4VvwXf5mniswrIUx-ToxUPvAw"}`
)

func TestProtocolSignatureVectors(t *testing.T) {
	publicKey, err := base64.RawURLEncoding.DecodeString(protocolVectorPublicKey)
	if err != nil {
		t.Fatalf("decode public key: %v", err)
	}
	tests := []struct {
		name      string
		response  string
		signature string
		sequence  uint64
	}{
		{name: "query", response: queryVectorResponse, signature: queryVectorSignature, sequence: 103},
		{name: "heartbeat", response: heartbeatVectorResponse, signature: heartbeatVectorSignature, sequence: 104},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			payload, signature, err := extractSignedPayloadBytes([]byte(tt.response), tt.signature)
			if err != nil {
				t.Fatalf("extract payload: %v", err)
			}
			if !ed25519.Verify(ed25519.PublicKey(publicKey), payload, signature) {
				t.Fatal("signature vector did not verify")
			}
			lease, err := decodeLeasePayload(payload)
			if err != nil {
				t.Fatalf("decode lease: %v", err)
			}
			if lease.Sequence != tt.sequence || lease.KeyID != "dev-key-2026-01" || lease.InstanceID != testInstanceID {
				t.Fatalf("lease = %#v", lease)
			}
			var raw map[string]json.RawMessage
			if err := json.Unmarshal([]byte(tt.response), &raw); err != nil {
				t.Fatalf("response JSON: %v", err)
			}
		})
	}
}
