package service

import (
	"testing"
)

func TestCreateServiceManager(t *testing.T) {
	tests := []struct {
		name        string
		expectError bool
	}{
		{
			name:        "CreateServiceManager",
			expectError: false, // 在支持的平台上不应该出错
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			sm, err := CreateServiceManager()

			if tt.expectError {
				if err == nil {
					t.Error("Expected error but got none")
				}
				if sm != nil {
					t.Error("Expected nil service manager on error")
				}
				return
			}

			if err != nil {
				t.Errorf("Unexpected error: %v", err)
				return
			}

			if sm == nil {
				t.Error("Service manager should not be nil")
				return
			}

			// 测试基本接口方法是否存在
			info := sm.GetPlatformInfo()
			if info == nil {
				t.Error("PlatformInfo should not be nil")
			}

			// 测试服务状态查询方法
			status := sm.GetServiceStatus()
			if status == nil {
				t.Error("ServiceStatus should not be nil")
			}

			// 测试服务配置方法
			config := sm.GetServiceConfig()
			if config == nil {
				t.Error("ServiceConfig should not be nil")
			}
		})
	}
}

func TestNewBaseServiceManager(t *testing.T) {
	detector := NewPlatformDetector()
	detector.Detect()

	bsm := NewBaseServiceManager(detector)

	if bsm == nil {
		t.Fatal("NewBaseServiceManager returned nil")
	}

	// 测试GetPlatformInfo
	retrievedInfo := bsm.GetPlatformInfo()
	if retrievedInfo == nil {
		t.Error("GetPlatformInfo should not return nil")
	}

	// 测试GetServiceConfig
	retrievedConfig := bsm.GetServiceConfig()
	if retrievedConfig == nil {
		t.Error("GetServiceConfig should not return nil")
	}

	// 验证配置的基本字段
	if retrievedConfig.ServiceName == "" {
		t.Error("ServiceName should not be empty")
	}

	if retrievedConfig.ExecPath == "" {
		t.Error("ExecPath should not be empty")
	}
}

func TestCheckExecutablePath(t *testing.T) {
	tests := []struct {
		name        string
		path        string
		expectError bool
	}{
		{
			name:        "Empty path",
			path:        "",
			expectError: true,
		},
		{
			name:        "Non-existent file",
			path:        "/non/existent/file",
			expectError: true,
		},
		{
			name:        "Existing executable",
			path:        "/bin/echo", // 假设这个文件存在
			expectError: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := checkExecutablePath(tt.path)

			if tt.expectError {
				if err == nil {
					t.Error("Expected error but got none")
				}
			} else {
				if err != nil {
					t.Errorf("Unexpected error: %v", err)
				}
			}
		})
	}
}

func TestEnsureLogDirectory(t *testing.T) {
	tests := []struct {
		name        string
		logFile     string
		expectError bool
	}{
		{
			name:        "Valid log file path",
			logFile:     "/tmp/test.log",
			expectError: false,
		},
		{
			name:        "Log file in subdirectory",
			logFile:     "/tmp/subdir/test.log",
			expectError: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := ensureLogDirectory(tt.logFile)

			if tt.expectError {
				if err == nil {
					t.Error("Expected error but got none")
				}
			} else {
				if err != nil {
					t.Errorf("Unexpected error: %v", err)
				}
			}
		})
	}
}

func TestCreateDefaultServiceConfig(t *testing.T) {
	detector := NewPlatformDetector()
	detector.Detect()

	config := createDefaultServiceConfig(detector)

	if config == nil {
		t.Fatal("createDefaultServiceConfig returned nil")
	}

	// 验证默认配置
	if config.ServiceName == "" {
		t.Error("ServiceName should not be empty")
	}

	if config.Description == "" {
		t.Error("Description should not be empty")
	}

	if config.ExecPath == "" {
		t.Error("ExecPath should not be empty")
	}

	if config.LogFile == "" {
		t.Error("LogFile should not be empty")
	}

	// 验证服务配置参数
	if len(config.Args) == 0 {
		t.Error("Args should not be empty")
	}

	if !config.Autostart {
		t.Error("Autostart should be true by default")
	}

	if config.RestartPolicy == "" {
		t.Error("RestartPolicy should not be empty")
	}

	if config.Environment == nil {
		t.Error("Environment should not be nil")
	}
}

func TestFormatServiceStatus(t *testing.T) {
	status := &ServiceStatus{
		Platform:    "Test Platform",
		ServiceName: "test-service",
		IsInstalled: true,
		IsRunning:   true,
		Autostart:   true,
		Status:      "running",
		Pid:         1234,
		Uptime:      "2h 30m",
	}

	formatted := FormatServiceStatus(status)

	if formatted == "" {
		t.Error("Formatted status should not be empty")
	}

	// 验证格式化结果包含关键信息（使用中文关键词）
	if !contains(formatted, "运行中") {
		t.Error("Formatted status should contain service status")
	}

	if !contains(formatted, "已安装") {
		t.Error("Formatted status should contain install status")
	}

	if !contains(formatted, "已启用") {
		t.Error("Formatted status should contain autostart status")
	}

	if !contains(formatted, "进程ID") {
		t.Error("Formatted status should contain process ID")
	}
}

// 辅助函数
func contains(s, substr string) bool {
	return len(s) >= len(substr) && (s == substr || len(s) > 0 &&
		(hasPrefix(s, substr) || hasSuffix(s, substr) || contains(s[1:], substr)))
}

func hasPrefix(s, prefix string) bool {
	return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
}

func hasSuffix(s, suffix string) bool {
	return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}
