package auth_test

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
	"senlinai-agent/backend/internal/config"
	"senlinai-agent/backend/internal/httpx"
	"senlinai-agent/backend/internal/logic/auth"
	"senlinai-agent/backend/internal/models"
)

func TestLoginHandlerReturnsSessionToken(t *testing.T) {
	newTestDB(t)
	service := auth.NewService("test-secret")
	invite, err := service.CreateInvite(1, "demo@senlin.ai")
	require.NoError(t, err)
	_, err = service.RegisterWithInvite(invite, "demo@senlin.ai", "Demo User", "password123")
	require.NoError(t, err)
	router := httpx.NewProtectedRouter(config.Config{Env: "test"}, service.VerifySession, auth.NewHandler(service))

	body, err := json.Marshal(gin.H{"email": "demo@senlin.ai", "password": "password123"})
	require.NoError(t, err)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusOK, rec.Code)
	var response struct {
		Token string `json:"token"`
	}
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))
	require.NotEmpty(t, response.Token)
	userID, err := service.VerifySession(response.Token)
	require.NoError(t, err)
	require.Equal(t, uint(1), userID)
}

func TestLoginHandlerRejectsInvalidCredentials(t *testing.T) {
	newTestDB(t)
	service := auth.NewService("test-secret")
	require.NoError(t, models.DBService.Create(&models.SenlinAgentUser{Email: "demo@senlin.ai", DisplayName: "Demo User", PasswordHash: "not-a-bcrypt-hash"}).Error)
	router := httpx.NewProtectedRouter(config.Config{Env: "test"}, service.VerifySession, auth.NewHandler(service))

	body, err := json.Marshal(gin.H{"email": "demo@senlin.ai", "password": "wrong"})
	require.NoError(t, err)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusUnauthorized, rec.Code)
	require.JSONEq(t, `{"error":{"code":"invalid_credentials","message":"邮箱或密码错误"}}`, rec.Body.String())
}

func TestLoginHandlerRejectsInvalidJSONWithStableError(t *testing.T) {
	newTestDB(t)
	service := auth.NewService("test-secret")
	router := httpx.NewProtectedRouter(config.Config{Env: "test"}, service.VerifySession, auth.NewHandler(service))
	req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewBufferString(`{"email":`))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusBadRequest, rec.Code)
	require.JSONEq(t, `{"error":{"code":"invalid_request","message":"请求参数无效"}}`, rec.Body.String())
}

func newTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	database, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, models.AutoMigrate(database))
	models.DBService = database
	return database
}
