package auth_test

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"
	"senlinai-agent/backend/internal/logic/auth"
)

func TestRequireUserReturnsStableErrorWhenBearerTokenIsMissing(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.Use(auth.RequireUser(func(string) (uint, error) { return 0, nil }))
	router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
	recorder := httptest.NewRecorder()

	router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/private", nil))

	require.Equal(t, http.StatusUnauthorized, recorder.Code)
	require.JSONEq(t, `{"error":{"code":"missing_bearer_token","message":"请先登录后再操作"}}`, recorder.Body.String())
}

func TestRequireUserReturnsStableErrorWhenBearerTokenIsInvalid(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.Use(auth.RequireUser(func(string) (uint, error) { return 0, errors.New("invalid") }))
	router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
	recorder := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/private", nil)
	req.Header.Set("Authorization", "Bearer invalid")

	router.ServeHTTP(recorder, req)

	require.Equal(t, http.StatusUnauthorized, recorder.Code)
	require.JSONEq(t, `{"error":{"code":"invalid_bearer_token","message":"登录状态无效或已过期，请重新登录"}}`, recorder.Body.String())
}
