package auth_test

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"testing"
	"time"

	"github.com/acp/interceptor/internal/auth"
	"github.com/golang-jwt/jwt/v5"
)

func TestValidateRS256(t *testing.T) {
	t.Parallel()
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	pubPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: x509.MarshalPKCS1PublicKey(&key.PublicKey),
	})
	pub, err := auth.LoadPublicKeyFromPEM(pubPEM)
	if err != nil {
		t.Fatal(err)
	}

	v, err := auth.NewValidator(auth.JWTConfig{
		Enabled:   true,
		Required:  true,
		Issuer:    "acp-dev",
		Audience:  "acp-interceptor",
		PublicKey: pub,
	})
	if err != nil {
		t.Fatal(err)
	}

	token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
		"sub":      "agent:fraud-analyst",
		"agent_id": "fraud-analyst",
		"roles":    []string{"fraud"},
		"iss":      "acp-dev",
		"aud":      "acp-interceptor",
		"exp":      time.Now().Add(time.Hour).Unix(),
	})
	signed, err := token.SignedString(key)
	if err != nil {
		t.Fatal(err)
	}

	p, err := v.Validate(signed)
	if err != nil {
		t.Fatal(err)
	}
	if p.AgentID != "fraud-analyst" {
		t.Fatalf("agent_id=%q", p.AgentID)
	}
}
