package service

import (
	"testing"
	"time"
)

func TestHashPasswordAndCheckPassword(t *testing.T) {
	hash, err := HashPassword("admin123")
	if err != nil {
		t.Fatalf("hash password: %v", err)
	}

	if !CheckPassword(hash, "admin123") {
		t.Fatal("expected password to match")
	}

	if CheckPassword(hash, "wrong-password") {
		t.Fatal("expected wrong password to fail")
	}
}

func TestAccessTokenRoundTrip(t *testing.T) {
	auth := NewAuthService("test-secret", time.Minute)
	token, _, err := auth.GenerateAccessToken(7, "admin", []string{"user:view", "user:create"})
	if err != nil {
		t.Fatalf("generate token: %v", err)
	}

	claims, err := auth.ParseAccessToken(token)
	if err != nil {
		t.Fatalf("parse token: %v", err)
	}

	if claims.UserID != 7 || claims.Username != "admin" {
		t.Fatalf("unexpected claims: %#v", claims)
	}

	if len(claims.Permissions) != 2 {
		t.Fatalf("unexpected permissions: %#v", claims.Permissions)
	}
}

func TestRefreshTokenHash(t *testing.T) {
	token, hash, err := NewRefreshToken()
	if err != nil {
		t.Fatalf("new refresh token: %v", err)
	}

	if token == "" || hash == "" {
		t.Fatal("expected token and hash")
	}

	if HashToken(token) != hash {
		t.Fatal("expected stable refresh token hash")
	}
}
