package security

import (
	"errors"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func TestGenerateAndParseWithIssuerRoundTrip(t *testing.T) {
	token, want, err := Generate("secret", "kra-admin", time.Hour, time.Minute, 7, 8, "uuid", "alice", "Alice", true, 9)
	if err != nil {
		t.Fatal(err)
	}
	got, err := ParseWithIssuer(token, "secret", "kra-admin")
	if err != nil {
		t.Fatal(err)
	}
	if got.ID != want.ID || got.Username != want.Username || got.Audience[0] != TokenAudience {
		t.Fatalf("claims = %#v, want %#v", got, want)
	}
}

func TestParseRejectsWrongIssuerAndAudience(t *testing.T) {
	token, _, err := Generate("secret", "kra-admin", time.Hour, time.Minute, 1, 1, "uuid", "user", "", false, 0)
	if err != nil {
		t.Fatal(err)
	}
	if _, err = ParseWithIssuer(token, "secret", "other"); !errors.Is(err, ErrTokenInvalid) {
		t.Fatalf("wrong issuer error = %v, want ErrTokenInvalid", err)
	}
	claims := &Claims{RegisteredClaims: jwt.RegisteredClaims{Audience: jwt.ClaimStrings{"other"}, Issuer: "kra-admin", IssuedAt: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Second)), ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}}
	token, err = Sign("secret", claims)
	if err != nil {
		t.Fatal(err)
	}
	if _, err = ParseWithIssuer(token, "secret", "kra-admin"); !errors.Is(err, ErrTokenInvalid) {
		t.Fatalf("wrong audience error = %v, want ErrTokenInvalid", err)
	}
}

func TestParseRejectsMissingRequiredTimeClaims(t *testing.T) {
	claims := &Claims{RegisteredClaims: jwt.RegisteredClaims{Audience: jwt.ClaimStrings{TokenAudience}, Issuer: "kra-admin"}}
	token, err := Sign("secret", claims)
	if err != nil {
		t.Fatal(err)
	}
	if _, err = ParseWithIssuer(token, "secret", "kra-admin"); !errors.Is(err, ErrTokenInvalid) {
		t.Fatalf("missing time claims error = %v, want ErrTokenInvalid", err)
	}
}

func TestSigningOptionsRejectInvalidValues(t *testing.T) {
	if _, _, err := Generate("", "kra", time.Hour, 0, 1, 1, "", "", "", false, 0); !errors.Is(err, ErrEmptySigningKey) {
		t.Fatalf("empty key error = %v", err)
	}
	if _, _, err := Generate("secret", "kra", 0, 0, 1, 1, "", "", "", false, 0); err == nil {
		t.Fatal("zero expiration was accepted")
	}
	if _, err := Sign("secret", nil); !errors.Is(err, ErrInvalidClaims) {
		t.Fatalf("nil claims error = %v", err)
	}
}

func TestParseRejectsAlgorithmConfusion(t *testing.T) {
	claims := &Claims{RegisteredClaims: jwt.RegisteredClaims{Audience: jwt.ClaimStrings{TokenAudience}, Issuer: "kra-admin", IssuedAt: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Second)), ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}}
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString([]byte("secret"))
	if err != nil {
		t.Fatal(err)
	}
	if _, err = ParseWithIssuer(token, "secret", "kra-admin"); !errors.Is(err, ErrTokenSignatureInvalid) {
		t.Fatalf("algorithm confusion error = %v, want ErrTokenSignatureInvalid", err)
	}
}
