package license
import "encoding/json"

import (
	"testing"
	"time"
)

func TestSignParseRoundTrip(t *testing.T) {
	key := "test-master-key-123"
	claims := Claims{Edition: EditionUltra, IssuedTo: "acme", MaxAccounts: 50,
		NotBefore: time.Now().Add(-time.Hour).Format(time.RFC3339),
		NotAfter:  time.Now().Add(24 * time.Hour).Format(time.RFC3339)}
	lic, err := Sign(claims, key)
	if err != nil {
		t.Fatal(err)
	}
	raw, _ := json.Marshal(lic)
	parsed, err := Parse(raw, deriveKey(key))
	if err != nil {
		t.Fatalf("parse: %v", err)
	}
	if parsed.Edition != EditionUltra || parsed.MaxAccounts != 50 {
		t.Fatalf("bad claims: %+v", parsed.Claims)
	}
}

func TestParseRejectsBadSignature(t *testing.T) {
	lic, _ := Sign(Claims{Edition: EditionPro, MaxAccounts: 30}, "key-a")
	raw, _ := json.Marshal(lic)
	if _, err := Parse(raw, deriveKey("key-b")); err == nil {
		t.Fatal("expected signature failure")
	}
}

func TestParseRejectsExpired(t *testing.T) {
	claims := Claims{Edition: EditionPro, MaxAccounts: 30,
		NotAfter: time.Now().Add(-time.Hour).Format(time.RFC3339)}
	lic, _ := Sign(claims, "key")
	raw, _ := json.Marshal(lic)
	if _, err := Parse(raw, deriveKey("key")); err != ErrLicenseExpired {
		t.Fatalf("expected expired, got %v", err)
	}
}
