package lint

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

func TestRetrieveModFile(t *testing.T) {
	t.Run("go.mod file exists", func(t *testing.T) {
		nestedDir := filepath.Join(t.TempDir(), "nested", "dir", "structure")
		err := os.MkdirAll(nestedDir, 0o750)
		if err != nil {
			t.Fatal(err)
		}

		modFilePath := filepath.Join(nestedDir, "go.mod")
		err = os.WriteFile(modFilePath, []byte("module example.com/test"), 0o600)
		if err != nil {
			t.Fatal(err)
		}
		foundPath, err := retrieveModFile(nestedDir)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if foundPath != modFilePath {
			t.Fatalf("expected %q, got %q", modFilePath, foundPath)
		}
	})

	t.Run("go.mod file does not exist", func(t *testing.T) {
		_, err := retrieveModFile(t.TempDir())
		if err == nil {
			t.Fatal("expected error, got nil")
		}
		expectedErrMsg := `did not found "go.mod" file`
		if err.Error() != expectedErrMsg {
			t.Fatalf("expected error message %q, got %q", expectedErrMsg, err.Error())
		}
	})
}

// TestIsGenerated tests isGenerated function.
func TestIsGenerated(t *testing.T) {
	tests := []struct {
		source    string
		generated bool
	}{
		{"// Code Generated by some tool. DO NOT EDIT.", false},
		{"// Code generated by some tool. DO NOT EDIT.", true},
		{"// Code generated by some tool. DO NOT EDIT", false},
		{"// Code generated  DO NOT EDIT.", true},
		{"// Code generated DO NOT EDIT.", false},
		{"\t\t// Code generated by some tool. DO NOT EDIT.\npackage foo\n", false},
		{"// Code generated by some tool. DO NOT EDIT.\npackage foo\n", true},
		{"package foo\n// Code generated by some tool. DO NOT EDIT.\ntype foo int\n", true},
		{"package foo\n // Code generated by some tool. DO NOT EDIT.\ntype foo int\n", false},
		{"package foo\n// Code generated by some tool. DO NOT EDIT. \ntype foo int\n", false},
		{"package foo\ntype foo int\n// Code generated by some tool. DO NOT EDIT.\n", true},
		{"package foo\ntype foo int\n// Code generated by some tool. DO NOT EDIT.", true},
	}

	for i, test := range tests {
		got := isGenerated([]byte(test.source))
		if got != test.generated {
			t.Errorf("test %d, isGenerated() = %v, want %v", i, got, test.generated)
		}
	}
}
