package miner

import (
	"strings"
	"testing"
)

func TestHashMeetsTargetEqual(t *testing.T) {
	target := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	hash := "0000000000000000000000000000000000000000000000000000000000000001"
	if !hashMeetsTarget(hash, target) {
		t.Fatal("lower hash should meet high target")
	}
}

func TestHashMeetsTargetReject(t *testing.T) {
	target := "0000000000000000000000000000000000000000000000000000000000000001"
	hash := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	if hashMeetsTarget(hash, target) {
		t.Fatal("high hash should not meet low target")
	}
}

func TestHashMeetsTargetExactMatch(t *testing.T) {
	val := "00000000000000000000000000000000000000000000000000000000000000ab"
	if !hashMeetsTarget(val, val) {
		t.Fatal("hash equal to target should meet target")
	}
}

func TestHashMeetsTargetInvalidHex(t *testing.T) {
	if hashMeetsTarget("not-hex", strings.Repeat("f", 64)) {
		t.Fatal("invalid hash hex should not meet target")
	}
	if hashMeetsTarget(strings.Repeat("f", 64), "zz") {
		t.Fatal("invalid target hex should not meet")
	}
	if hashMeetsTarget("", strings.Repeat("f", 64)) {
		t.Fatal("empty hash should not meet target")
	}
}

func TestHashMeetsTargetShortTargetPadded(t *testing.T) {
	// Short target hex is zero-padded to hash width
	target := "ff"
	hash := strings.Repeat("0", 63) + "1"
	if !hashMeetsTarget(hash, target) {
		t.Fatal("padded short target should accept low hash")
	}
}

func TestPadHex(t *testing.T) {
	if got := padHex("ab", 6); got != "0000ab" {
		t.Fatalf("padHex = %q", got)
	}
	if got := padHex("abcdef", 4); got != "abcdef" {
		t.Fatalf("no truncate when already long: %q", got)
	}
}

func TestReverseBytes(t *testing.T) {
	in := []byte{1, 2, 3, 4}
	out := reverseBytes(in)
	want := []byte{4, 3, 2, 1}
	for i := range want {
		if out[i] != want[i] {
			t.Fatalf("reverseBytes = %v, want %v", out, want)
		}
	}
}
