package rediskeys

import (
	"strings"
	"testing"
)

func TestWorkerKey(t *testing.T) {
	tests := []struct {
		name        string
		prefix      string
		purpose     string
		id          string
		expectedKey string
		expectError bool
	}{
		{
			name:        "Standard key generation",
			prefix:      "alt",
			purpose:     "job",
			id:          "123",
			expectedKey: "alt:worker:job:123",
			expectError: false,
		},
		{
			name:        "Case normalization",
			prefix:      "ALT",
			purpose:     "JOB",
			id:          "abc-DEF",
			expectedKey: "alt:worker:job:abc-DEF",
			expectError: false,
		},
		{
			name:        "Whitespace and colon trimming",
			prefix:      "  alt:  ",
			purpose:     "  :job:  ",
			id:          "  123  ",
			expectedKey: "alt:worker:job:123",
			expectError: false,
		},
		{
			name:        "Empty prefix fallback",
			prefix:      "",
			purpose:     "job",
			id:          "123",
			expectedKey: "alt:worker:job:123",
			expectError: false,
		},
		{
			name:        "Empty purpose rejection",
			prefix:      "alt",
			purpose:     "",
			id:          "123",
			expectedKey: "",
			expectError: true,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			key, err := WorkerKey(tc.prefix, tc.purpose, tc.id)
			if tc.expectError {
				if err == nil {
					t.Errorf("expected error, but got nil and key %q", key)
				}
			} else {
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}
				if key != tc.expectedKey {
					t.Errorf("expected key %q, got %q", tc.expectedKey, key)
				}
			}
		})
	}
}

func TestWorkerKeyRejectsEmptyID(t *testing.T) {
	invalidIDs := []string{"", "   ", "\t", " : : "}
	for _, id := range invalidIDs {
		key, err := WorkerKey("alt", "job", id)
		if err == nil {
			t.Errorf("expected error for empty/whitespace ID %q, but got nil and key %q", id, key)
		} else if !strings.Contains(err.Error(), "id cannot be empty") {
			t.Errorf("expected ID empty error message, got %v", err)
		}
	}
}
