package ssh

import (
	"path/filepath"
	"testing"

	"github.com/vstockwell/wraith/internal/db"
)

func setupHostKeyStore(t *testing.T) *HostKeyStore {
	t.Helper()
	d, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
	if err != nil {
		t.Fatal(err)
	}
	if err := db.Migrate(d); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { d.Close() })
	return NewHostKeyStore(d)
}

func TestVerifyNewHost(t *testing.T) {
	store := setupHostKeyStore(t)
	result, err := store.Verify("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123")
	if err != nil {
		t.Fatal(err)
	}
	if result != HostKeyNew {
		t.Errorf("got %d, want HostKeyNew", result)
	}
}

func TestStoreAndVerifyMatch(t *testing.T) {
	store := setupHostKeyStore(t)
	if err := store.Store("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123", "AAAA..."); err != nil {
		t.Fatal(err)
	}
	result, err := store.Verify("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123")
	if err != nil {
		t.Fatal(err)
	}
	if result != HostKeyMatch {
		t.Errorf("got %d, want HostKeyMatch", result)
	}
}

func TestVerifyChangedKey(t *testing.T) {
	store := setupHostKeyStore(t)
	if err := store.Store("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123", "AAAA..."); err != nil {
		t.Fatal(err)
	}
	result, err := store.Verify("192.168.1.4", 22, "ssh-ed25519", "SHA256:DIFFERENT")
	if err != nil {
		t.Fatal(err)
	}
	if result != HostKeyChanged {
		t.Errorf("got %d, want HostKeyChanged", result)
	}
}

func TestDeleteHostKey(t *testing.T) {
	store := setupHostKeyStore(t)
	if err := store.Store("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123", "AAAA..."); err != nil {
		t.Fatal(err)
	}
	if err := store.Delete("192.168.1.4", 22); err != nil {
		t.Fatal(err)
	}
	result, err := store.Verify("192.168.1.4", 22, "ssh-ed25519", "SHA256:abc123")
	if err != nil {
		t.Fatal(err)
	}
	if result != HostKeyNew {
		t.Errorf("after delete, got %d, want HostKeyNew", result)
	}
}
