package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"testing"
	"time"
)

// makeToken creates a valid HMAC-SHA256 token: sig.timestamp
func makeToken(secret string, ts int64) string {
	tsStr := fmt.Sprintf("%d", ts)
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(tsStr))
	sig := hex.EncodeToString(mac.Sum(nil))
	return sig + "." + tsStr
}

func TestValidateToken_Valid(t *testing.T) {
	secret := "test-secret"
	ts := time.Now().Unix()
	token := makeToken(secret, ts)

	if !ValidateToken(token, secret, 30) {
		t.Error("expected valid token to pass validation")
	}
}

func TestValidateToken_Expired(t *testing.T) {
	secret := "test-secret"
	ts := time.Now().Unix() - 60 // 60 seconds ago
	token := makeToken(secret, ts)

	if ValidateToken(token, secret, 30) {
		t.Error("expected expired token (60s ago) to be rejected")
	}
}

func TestValidateToken_WrongSecret(t *testing.T) {
	ts := time.Now().Unix()
	token := makeToken("right-secret", ts)

	if ValidateToken(token, "wrong-secret", 30) {
		t.Error("expected token signed with wrong secret to be rejected")
	}
}

func TestValidateToken_MalformedNoTimestamp(t *testing.T) {
	// No dot separator — cannot split into sig.timestamp
	if ValidateToken("nodothere", "secret", 30) {
		t.Error("expected malformed token (no dot) to be rejected")
	}
}

func TestValidateToken_EmptyToken(t *testing.T) {
	if ValidateToken("", "secret", 30) {
		t.Error("expected empty token to be rejected")
	}
}
