package passgen

import (
	"bytes"
	"io"
	"strings"
	"testing"
)

func TestGenerateUsesRequestedLengthAndAlphabet(t *testing.T) {
	opts := Options{
		Length:    64,
		UseLower:  true,
		UseUpper:  false,
		UseDigits: false,
	}

	password, err := Generate(opts)
	if err != nil {
		t.Fatalf("Generate returned error: %v", err)
	}

	if len(password) != opts.Length {
		t.Fatalf("password length = %d, want %d", len(password), opts.Length)
	}

	for _, ch := range password {
		if !strings.ContainsRune(lowerChars, ch) {
			t.Fatalf("password contains character outside requested alphabet: %q", ch)
		}
	}
}

func TestGenerateRejectsEmptyAlphabet(t *testing.T) {
	_, err := Generate(Options{Length: 24})
	if err != ErrEmptyAlphabet {
		t.Fatalf("Generate error = %v, want %v", err, ErrEmptyAlphabet)
	}
}

func TestGenerateUsesProvidedRandomReader(t *testing.T) {
	opts := Options{
		Length:     3,
		UseLower:   true,
		UseUpper:   false,
		UseDigits:  false,
		UseSymbols: false,
		Random:     bytes.NewReader([]byte{0, 1, 2}),
	}

	password, err := Generate(opts)
	if err != nil {
		t.Fatalf("Generate returned error: %v", err)
	}

	if password != "abc" {
		t.Fatalf("password = %q, want %q", password, "abc")
	}
}

func TestGenerateReturnsRandomReaderError(t *testing.T) {
	opts := Options{
		Length:     1,
		UseLower:   true,
		UseUpper:   false,
		UseDigits:  false,
		UseSymbols: false,
		Random:     strings.NewReader(""),
	}

	if _, err := Generate(opts); err == nil {
		t.Fatalf("Generate returned nil error")
	} else if !strings.Contains(err.Error(), io.EOF.Error()) {
		t.Fatalf("Generate error = %v, want EOF context", err)
	}
}
