package autoregister

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

	"github.com/go-grpc-kit/go-grpc-kit/pkg/config"
	"go.uber.org/zap"
)

// TestAutoRegisterIntegration 测试自动注册功能的完整工作流程
func TestAutoRegisterIntegration(t *testing.T) {
	// 创建临时目录结构
	tempDir := t.TempDir()
	servicesDir := filepath.Join(tempDir, "services")
	err := os.MkdirAll(servicesDir, 0755)
	if err != nil {
		t.Fatalf("Failed to create services directory: %v", err)
	}

	// 创建示例服务文件
	userServiceContent := `package services

import "google.golang.org/grpc"

// UserService 用户服务
// @grpc-service UserService
type UserService struct{}

func (s *UserService) RegisterService(server grpc.ServiceRegistrar) {
	// 注册逻辑
}
`

	orderServiceContent := `package services

import "google.golang.org/grpc"

type OrderService struct{}

func (s *OrderService) RegisterService(server grpc.ServiceRegistrar) {
	// 注册逻辑
}
`

	paymentServiceContent := `package services

type PaymentGatewayService struct{}
`

	// 写入服务文件
	files := map[string]string{
		"user_service.go":    userServiceContent,
		"order_service.go":   orderServiceContent,
		"payment_service.go": paymentServiceContent,
	}

	for filename, content := range files {
		filePath := filepath.Join(servicesDir, filename)
		err := os.WriteFile(filePath, []byte(content), 0644)
		if err != nil {
			t.Fatalf("Failed to create %s: %v", filename, err)
		}
	}

	// 配置自动注册
	cfg := &config.AutoRegisterConfig{
		Enabled:     true,
		ScanDirs:    []string{servicesDir},
		Patterns:    []string{"*.go"},
		Excludes:    []string{"*_test.go"},
		ServiceName: "", // 使用默认命名规则
	}

	logger := zap.NewNop()
	autoRegister := NewAutoRegister(cfg, logger)

	// 执行扫描和生成
	outputPath := filepath.Join(tempDir, "auto_register_generated.go")
	err = autoRegister.ScanAndGenerate(outputPath)
	if err != nil {
		t.Fatalf("Failed to scan and generate: %v", err)
	}

	// 验证生成的文件存在
	if _, err := os.Stat(outputPath); os.IsNotExist(err) {
		t.Fatal("Generated file does not exist")
	}

	// 读取生成的文件内容
	content, err := os.ReadFile(outputPath)
	if err != nil {
		t.Fatalf("Failed to read generated file: %v", err)
	}

	contentStr := string(content)

	// 验证生成的代码包含预期的内容
	expectedContents := []string{
		"// Code generated by go-grpc-kit autoregister. DO NOT EDIT.",
		"package main",
		"func AutoRegisterServices(server grpc.ServiceRegistrar)",
		"func GetAutoRegisteredServices() []string",
		"UserService",
		"OrderService", 
		"PaymentGatewayService",
		"services.RegisteruserServer",
		"services.RegisterorderServer",
		"services.RegisterpaymentgatewayServer",
	}

	for _, expected := range expectedContents {
		if !strings.Contains(contentStr, expected) {
			t.Errorf("Generated code should contain '%s'", expected)
		}
	}

	// 验证服务列表
	expectedServices := []string{
		`"user"`,
		`"order"`,
		`"paymentgateway"`,
	}

	for _, expectedService := range expectedServices {
		if !strings.Contains(contentStr, expectedService) {
			t.Errorf("Generated code should contain service '%s'", expectedService)
		}
	}

	t.Logf("Integration test passed. Generated file:\n%s", contentStr)
}

// TestAutoRegisterIntegrationWithCustomPattern 测试使用自定义服务名称模式的集成
func TestAutoRegisterIntegrationWithCustomPattern(t *testing.T) {
	// 创建临时目录
	tempDir := t.TempDir()
	servicesDir := filepath.Join(tempDir, "services")
	err := os.MkdirAll(servicesDir, 0755)
	if err != nil {
		t.Fatalf("Failed to create services directory: %v", err)
	}

	// 创建示例服务文件
	serviceContent := `package services

type TestService struct{}
`

	serviceFile := filepath.Join(servicesDir, "test_service.go")
	err = os.WriteFile(serviceFile, []byte(serviceContent), 0644)
	if err != nil {
		t.Fatalf("Failed to create service file: %v", err)
	}

	// 配置自动注册（使用自定义服务名称模式）
	cfg := &config.AutoRegisterConfig{
		Enabled:     true,
		ScanDirs:    []string{servicesDir},
		Patterns:    []string{"*.go"},
		Excludes:    []string{"*_test.go"},
		ServiceName: "api-{type}-v1", // 自定义模式
	}

	logger := zap.NewNop()
	autoRegister := NewAutoRegister(cfg, logger)

	// 执行扫描和生成
	outputPath := filepath.Join(tempDir, "custom_auto_register.go")
	err = autoRegister.ScanAndGenerate(outputPath)
	if err != nil {
		t.Fatalf("Failed to scan and generate with custom pattern: %v", err)
	}

	// 读取生成的文件内容
	content, err := os.ReadFile(outputPath)
	if err != nil {
		t.Fatalf("Failed to read generated file: %v", err)
	}

	contentStr := string(content)

	// 验证自定义服务名称模式
	expectedServiceName := "api-TestService-v1"
	if !strings.Contains(contentStr, expectedServiceName) {
		t.Errorf("Generated code should contain custom service name '%s'", expectedServiceName)
	}

	t.Logf("Custom pattern integration test passed. Generated service name: %s", expectedServiceName)
}

// TestAutoRegisterIntegrationDisabled 测试禁用状态下的行为
func TestAutoRegisterIntegrationDisabled(t *testing.T) {
	tempDir := t.TempDir()

	// 配置自动注册（禁用状态）
	cfg := &config.AutoRegisterConfig{
		Enabled:  false,
		ScanDirs: []string{tempDir},
	}

	logger := zap.NewNop()
	autoRegister := NewAutoRegister(cfg, logger)

	// 执行扫描和生成
	outputPath := filepath.Join(tempDir, "disabled_auto_register.go")
	err := autoRegister.ScanAndGenerate(outputPath)
	if err != nil {
		t.Fatalf("Disabled auto-register should not return error: %v", err)
	}

	// 验证没有生成文件
	if _, err := os.Stat(outputPath); !os.IsNotExist(err) {
		t.Error("No file should be generated when auto-register is disabled")
	}
}