package ident

import (
	"strings"
	"testing"
	"time"
)

func TestNewIDLowercaseAndValid(t *testing.T) {
	id := NewID()
	if len(id) != 26 {
		t.Fatalf("len(%q) = %d, want 26", id, len(id))
	}
	if id != strings.ToLower(id) {
		t.Fatalf("id %q is not lowercase", id)
	}
	if _, err := Parse(id); err != nil {
		t.Fatalf("Parse(NewID()) failed: %v", err)
	}
}

func TestNewIDSortedByIssueOrder(t *testing.T) {
	prev := NewID()
	for range 100 {
		next := NewID()
		if next <= prev {
			t.Fatalf("ids out of order: %q then %q", prev, next)
		}
		prev = next
	}
}

func TestNewIDAtEqualTimestampsKeepOrder(t *testing.T) {
	ts := time.Date(2026, 7, 2, 12, 0, 0, 0, time.UTC)
	prev := NewIDAt(ts)
	for range 100 {
		next := NewIDAt(ts) // одна и та же миллисекунда → monotonic-энтропия
		if next <= prev {
			t.Fatalf("ids out of order at equal timestamp: %q then %q", prev, next)
		}
		prev = next
	}
}

func TestNewIDAtChronology(t *testing.T) {
	older := NewIDAt(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
	newer := NewIDAt(time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC))
	if older >= newer {
		t.Fatalf("chronology broken: %q >= %q", older, newer)
	}
}

func TestParseNormalizesCase(t *testing.T) {
	id := NewID()
	got, err := Parse(strings.ToUpper(id))
	if err != nil {
		t.Fatalf("Parse(upper) failed: %v", err)
	}
	if got != id {
		t.Fatalf("Parse(upper) = %q, want %q", got, id)
	}
}

func TestParseRejectsGarbage(t *testing.T) {
	for _, bad := range []string{"", "abc", "abc!!!", "123", strings.Repeat("z", 26), strings.Repeat("a", 27)} {
		if _, err := Parse(bad); err == nil {
			t.Fatalf("Parse(%q) unexpectedly succeeded", bad)
		}
	}
}
