package scanner

import (
	"os"
	"path/filepath"
	"testing"
)

func TestLoadSubdomainList_FileNotExists(t *testing.T) {
	// Should fall back to DefaultSubdomains when file doesn't exist
	names := loadSubdomainList("/tmp/nonexistent-path-aasd-test")
	if len(names) == 0 {
		t.Error("expected fallback list, got empty")
	}
	if len(names) != len(DefaultSubdomains) {
		t.Errorf("expected %d default names, got %d", len(DefaultSubdomains), len(names))
	}
}

func TestLoadSubdomainList_FileExists(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "subdomains.txt")
	content := "# comment line\napi\nwww\n  admin  \n\nMAIL\n"
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	names := loadSubdomainList(dir)
	if len(names) != 4 {
		t.Fatalf("expected 4 names (api, www, admin, mail), got %d: %v", len(names), names)
	}
	if names[0] != "api" {
		t.Errorf("expected first name 'api', got '%s'", names[0])
	}
	// Verify dedup (MAIL → mail should be same as an existing entry if present)
	// Actually the content is: api, www, admin, MAIL - MAIL is not a duplicate
	if names[3] != "mail" {
		t.Errorf("expected last name 'mail', got '%s'", names[3])
	}
}

func TestLoadSubdomainList_EmptyFile(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "subdomains.txt")
	if err := os.WriteFile(path, []byte(""), 0644); err != nil {
		t.Fatal(err)
	}

	names := loadSubdomainList(dir)
	if len(names) == 0 {
		t.Error("expected fallback list for empty file")
	}
}

func TestLoadSubdomainList_CommentsOnly(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "subdomains.txt")
	content := "# this is a comment\n# another comment\n  # indented comment\n"
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	names := loadSubdomainList(dir)
	if len(names) == 0 {
		t.Error("expected fallback list for comments-only file")
	}
}

func TestLoadSubdomainList_Deduplication(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "subdomains.txt")
	content := "api\nwww\napi\nAPI\nApi\n"
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	names := loadSubdomainList(dir)
	if len(names) != 2 {
		t.Errorf("expected 2 unique names (api, www), got %d: %v", len(names), names)
	}
}

func TestDefaultSubdomains_NotEmpty(t *testing.T) {
	if len(DefaultSubdomains) == 0 {
		t.Error("DefaultSubdomains should not be empty")
	}
	// Check first few well-known entries
	expected := []string{"api", "www", "admin", "mail"}
	for _, e := range expected {
		found := false
		for _, d := range DefaultSubdomains {
			if d == e {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("expected '%s' in DefaultSubdomains", e)
		}
	}
}
