package middleware

import (
	"io"
	"net/http/httptest"
	"testing"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/requestid"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/logger"
)

// TestRecover_PanicCapture 测试 panic 捕获功能
func TestRecover_PanicCapture(t *testing.T) {
	// 初始化日志器
	_ = logger.InitLoggers(
		"debug",
		true,
		logger.LogRotationConfig{
			Filename:   "../../tests/integration/logs/recover_test.log",
			MaxSize:    10,
			MaxBackups: 3,
			MaxAge:     7,
			Compress:   false,
		},
		logger.LogRotationConfig{
			Filename:   "../../tests/integration/logs/access_test.log",
			MaxSize:    10,
			MaxBackups: 3,
			MaxAge:     7,
			Compress:   false,
		},
	)

	appLogger := logger.GetAppLogger()

	app := fiber.New(fiber.Config{
		ErrorHandler: errors.SafeErrorHandler(appLogger),
	})

	// 注册 recover 中间件
	app.Use(Recover(appLogger))
	app.Use(requestid.New(requestid.Config{
		Generator: func() string {
			return uuid.NewString()
		},
	}))

	// 创建会触发 panic 的路由
	app.Get("/panic", func(c *fiber.Ctx) error {
		panic("测试 panic")
	})

	// 发起请求
	req := httptest.NewRequest("GET", "/panic", nil)
	resp, err := app.Test(req, -1)
	require.NoError(t, err)
	defer func() { _ = resp.Body.Close() }()

	// 验证响应状态码为 500 (内部错误)
	assert.Equal(t, 500, resp.StatusCode, "panic 应转换为 500 错误")

	// 验证响应体不为空
	body, err := io.ReadAll(resp.Body)
	require.NoError(t, err)
	assert.NotEmpty(t, body, "panic 响应体不应为空")

	t.Log("✓ Panic 捕获测试通过")
}

// TestRecover_NilPointerPanic 测试空指针 panic
func TestRecover_NilPointerPanic(t *testing.T) {
	appLogger := logger.GetAppLogger()

	app := fiber.New(fiber.Config{
		ErrorHandler: errors.SafeErrorHandler(appLogger),
	})

	app.Use(Recover(appLogger))
	app.Use(requestid.New(requestid.Config{
		Generator: func() string {
			return uuid.NewString()
		},
	}))

	// 创建会触发空指针 panic 的路由
	app.Get("/nil-panic", func(c *fiber.Ctx) error {
		var ptr *string
		_ = *ptr // 空指针引用会导致 panic
		return nil
	})

	req := httptest.NewRequest("GET", "/nil-panic", nil)
	resp, err := app.Test(req, -1)
	require.NoError(t, err)
	defer func() { _ = resp.Body.Close() }()

	assert.Equal(t, 500, resp.StatusCode, "空指针 panic 应转换为 500 错误")

	t.Log("✓ 空指针 Panic 捕获测试通过")
}

// TestRecover_NormalRequest 测试正常请求不受影响
func TestRecover_NormalRequest(t *testing.T) {
	appLogger := logger.GetAppLogger()

	app := fiber.New(fiber.Config{
		ErrorHandler: errors.SafeErrorHandler(appLogger),
	})

	app.Use(Recover(appLogger))

	// 创建正常的路由
	app.Get("/normal", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{"status": "ok"})
	})

	req := httptest.NewRequest("GET", "/normal", nil)
	resp, err := app.Test(req, -1)
	require.NoError(t, err)
	defer func() { _ = resp.Body.Close() }()

	assert.Equal(t, 200, resp.StatusCode, "正常请求应返回 200")

	t.Log("✓ 正常请求测试通过")
}
