package service

import (
	"reflect"
	"strings"
	"testing"
)

func TestRandomUsernameLengthAndCharacters(t *testing.T) {
	for range 200 {
		username, err := randomUsername()
		if err != nil {
			t.Fatalf("randomUsername returned error: %v", err)
		}
		if len(username) < 5 || len(username) > 12 {
			t.Fatalf("username length must be 5 to 12, got %q", username)
		}
		for _, character := range username {
			if !strings.ContainsRune(usernameAlphabet, character) {
				t.Fatalf("username contains unsupported character: %q", username)
			}
		}
	}
}

func TestBuildBatchAccounts(t *testing.T) {
	accounts, err := buildBatchAccounts("RR", "001", "003")
	if err != nil {
		t.Fatalf("buildBatchAccounts returned error: %v", err)
	}
	want := []string{"RR-001", "RR-002", "RR-003"}
	if !reflect.DeepEqual(accounts, want) {
		t.Fatalf("accounts = %#v, want %#v", accounts, want)
	}
}

func TestBuildBatchAccountsUsesWidestSequence(t *testing.T) {
	accounts, err := buildBatchAccounts("A", "1", "003")
	if err != nil {
		t.Fatalf("buildBatchAccounts returned error: %v", err)
	}
	want := []string{"A-001", "A-002", "A-003"}
	if !reflect.DeepEqual(accounts, want) {
		t.Fatalf("accounts = %#v, want %#v", accounts, want)
	}
}

func TestBuildBatchAccountsAllowsFiftyUsers(t *testing.T) {
	accounts, err := buildBatchAccounts("RR", "001", "050")
	if err != nil {
		t.Fatalf("buildBatchAccounts returned error: %v", err)
	}
	if len(accounts) != 50 || accounts[0] != "RR-001" || accounts[49] != "RR-050" {
		t.Fatalf("unexpected account range: first=%q last=%q count=%d", accounts[0], accounts[len(accounts)-1], len(accounts))
	}
}

func TestBuildBatchAccountsValidation(t *testing.T) {
	tests := []struct {
		name   string
		prefix string
		start  string
		end    string
	}{
		{name: "empty prefix", start: "001", end: "002"},
		{name: "non numeric start", prefix: "RR", start: "A01", end: "002"},
		{name: "start after end", prefix: "RR", start: "003", end: "002"},
		{name: "more than fifty", prefix: "RR", start: "001", end: "051"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if _, err := buildBatchAccounts(test.prefix, test.start, test.end); err == nil {
				t.Fatal("expected validation error")
			}
		})
	}
}
