package bootstrap

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

	"github.com/break/junhong_cmp_fiber/pkg/config"
)

func TestEnsureDirectories_Success(t *testing.T) {
	tmpDir := t.TempDir()
	cfg := &config.Config{
		Storage: config.StorageConfig{
			TempDir: filepath.Join(tmpDir, "storage"),
		},
		Logging: config.LoggingConfig{
			AppLog:    config.LogRotationConfig{Filename: filepath.Join(tmpDir, "logs", "app.log")},
			AccessLog: config.LogRotationConfig{Filename: filepath.Join(tmpDir, "logs", "access.log")},
		},
	}

	result, err := EnsureDirectories(cfg, nil)
	if err != nil {
		t.Fatalf("EnsureDirectories() 失败: %v", err)
	}

	if result.TempDir != cfg.Storage.TempDir {
		t.Errorf("TempDir 期望 %s, 实际 %s", cfg.Storage.TempDir, result.TempDir)
	}
	if result.AppLogDir != filepath.Join(tmpDir, "logs") {
		t.Errorf("AppLogDir 期望 %s, 实际 %s", filepath.Join(tmpDir, "logs"), result.AppLogDir)
	}

	if _, err := os.Stat(result.TempDir); os.IsNotExist(err) {
		t.Error("TempDir 目录未创建")
	}
	if _, err := os.Stat(result.AppLogDir); os.IsNotExist(err) {
		t.Error("AppLogDir 目录未创建")
	}
}

func TestEnsureDirectories_ExistingDirs(t *testing.T) {
	tmpDir := t.TempDir()
	storageDir := filepath.Join(tmpDir, "storage")
	os.MkdirAll(storageDir, 0755)

	cfg := &config.Config{
		Storage: config.StorageConfig{TempDir: storageDir},
		Logging: config.LoggingConfig{
			AppLog:    config.LogRotationConfig{Filename: filepath.Join(tmpDir, "logs", "app.log")},
			AccessLog: config.LogRotationConfig{Filename: filepath.Join(tmpDir, "logs", "access.log")},
		},
	}

	result, err := EnsureDirectories(cfg, nil)
	if err != nil {
		t.Fatalf("EnsureDirectories() 失败: %v", err)
	}

	if result.TempDir != storageDir {
		t.Errorf("已存在目录应返回原路径")
	}
}

func TestEnsureDirectories_EmptyPaths(t *testing.T) {
	cfg := &config.Config{
		Storage: config.StorageConfig{TempDir: ""},
		Logging: config.LoggingConfig{
			AppLog:    config.LogRotationConfig{Filename: ""},
			AccessLog: config.LogRotationConfig{Filename: ""},
		},
	}

	result, err := EnsureDirectories(cfg, nil)
	if err != nil {
		t.Fatalf("EnsureDirectories() 空路径时不应失败: %v", err)
	}

	if len(result.Fallbacks) != 0 {
		t.Error("空路径不应产生降级")
	}
}

func TestEnsureDirectory_Fallback(t *testing.T) {
	path, fallback, err := ensureDirectory("/root/no_permission_dir_test_"+t.Name(), nil)
	if err != nil {
		if os.Getuid() == 0 {
			t.Skip("以 root 身份运行，跳过权限测试")
		}
		t.Skip("无法测试权限降级场景")
	}

	if fallback {
		if !filepath.HasPrefix(path, os.TempDir()) {
			t.Errorf("降级路径应在临时目录下，实际: %s", path)
		}
		os.RemoveAll(path)
	}
}
