package api

import (
	"testing"
	"time"
)

func TestSignStreamToken_RoundTrip(t *testing.T) {
	secret := []byte("test-secret-not-real")
	trackID := "abc-123"
	exp := time.Now().Unix() + 3600

	token := SignStreamToken(secret, trackID, exp)
	if token == "" {
		t.Fatal("got empty token")
	}
	if !VerifyStreamToken(secret, trackID, exp, token) {
		t.Fatal("round-trip verify failed")
	}
}

func TestVerifyStreamToken_TamperedTokenRejected(t *testing.T) {
	secret := []byte("test-secret")
	trackID := "abc-123"
	exp := time.Now().Unix() + 3600

	token := SignStreamToken(secret, trackID, exp)
	// Flip a hex digit anywhere in the middle.
	mid := len(token) / 2
	tampered := token[:mid] + flipHexDigit(token[mid:mid+1]) + token[mid+1:]

	if VerifyStreamToken(secret, trackID, exp, tampered) {
		t.Fatal("verify accepted tampered token")
	}
}

func TestVerifyStreamToken_ExpiredRejected(t *testing.T) {
	secret := []byte("test-secret")
	trackID := "abc-123"
	exp := time.Now().Unix() - 1 // already expired

	token := SignStreamToken(secret, trackID, exp)
	if VerifyStreamToken(secret, trackID, exp, token) {
		t.Fatal("verify accepted expired token")
	}
}

func TestVerifyStreamToken_WrongTrackIDRejected(t *testing.T) {
	secret := []byte("test-secret")
	exp := time.Now().Unix() + 3600

	token := SignStreamToken(secret, "track-a", exp)
	if VerifyStreamToken(secret, "track-b", exp, token) {
		t.Fatal("verify accepted token for different track")
	}
}

func TestVerifyStreamToken_WrongSecretRejected(t *testing.T) {
	trackID := "abc-123"
	exp := time.Now().Unix() + 3600

	token := SignStreamToken([]byte("secret-a"), trackID, exp)
	if VerifyStreamToken([]byte("secret-b"), trackID, exp, token) {
		t.Fatal("verify accepted token signed with different secret")
	}
}

func flipHexDigit(s string) string {
	if s == "" {
		return s
	}
	switch s[0] {
	case '0':
		return "1"
	default:
		return "0"
	}
}
