package api

import (
	"testing"
)

func TestCheckPasswordBcryptAndLegacy(t *testing.T) {
	hashed, err := hashPassword("secret123")
	if err != nil {
		t.Fatal(err)
	}
	if !checkPassword(hashed, "secret123") {
		t.Fatal("bcrypt hash should match correct password")
	}
	if checkPassword(hashed, "wrong") {
		t.Fatal("bcrypt hash should reject wrong password")
	}
	if !checkPassword("plainlegacy", "plainlegacy") {
		t.Fatal("legacy plain-text should match")
	}
	if checkPassword("plainlegacy", "other") {
		t.Fatal("legacy plain-text should reject mismatch")
	}
}

func TestIsBcryptHash(t *testing.T) {
	h, _ := hashPassword("x")
	if !isBcryptHash(h) {
		t.Fatal("expected bcrypt prefix")
	}
	if isBcryptHash("plaintext") {
		t.Fatal("plaintext should not look like bcrypt")
	}
}

func TestAuthCacheHitAndMiss(t *testing.T) {
	user, pass := "cacheuser", "cachepass"
	if authCacheHit(user, pass) {
		t.Fatal("cache should miss before set")
	}
	authCacheSet(user, pass)
	if !authCacheHit(user, pass) {
		t.Fatal("cache should hit after set")
	}
	if authCacheHit(user, "wrong") {
		t.Fatal("different password should miss")
	}
}

func TestGenerateRandomPasswordLength(t *testing.T) {
	pw := generateRandomPassword()
	if len(pw) != 8 {
		t.Fatalf("expected 8-char hex password, got len %d (%q)", len(pw), pw)
	}
}

func TestAgentForgeConfigDefaults(t *testing.T) {
	cfg := AgentForgeConfig{}
	if cfg.poolHostOrDefault("fallback.host") != "fallback.host" {
		t.Fatal("empty pool host should use fallback")
	}
	if cfg.poolPortOrDefault(3333) != 3333 {
		t.Fatal("zero pool port should use fallback")
	}
	cfg = AgentForgeConfig{PoolHost: "pool.example.com", PoolPort: 443}
	if cfg.poolHostOrDefault("fallback") != "pool.example.com" {
		t.Fatal("explicit pool host should win")
	}
	if cfg.poolPortOrDefault(3333) != 443 {
		t.Fatal("explicit pool port should win")
	}
}
