package unit

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

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"ai-myopia-prevention/api/handlers"
)

func TestAuthHandlers(t *testing.T) {
	// 设置Gin为测试模式
	gin.SetMode(gin.TestMode)

	// 创建内存数据库用于测试
	db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
	if err != nil {
		t.Fatalf("failed to connect database: %v", err)
	}

	// 迁移模型
	err = db.AutoMigrate(&struct {
		ID           uint   `gorm:"primaryKey"`
		Username     string `gorm:"uniqueIndex"`
		PasswordHash string
		Phone        string `gorm:"uniqueIndex"`
		UserType     string
		UserID       uint
		Status       int
	}{})
	if err != nil {
		t.Fatalf("failed to migrate database: %v", err)
	}

	// 创建服务实例
	authService := handlers.NewAuthService(db)

	t.Run("Test Login Endpoint", func(t *testing.T) {
		// 创建测试路由
		router := gin.Default()
		router.POST("/login", authService.Login)

		// 准备测试数据
		loginReq := handlers.LoginRequest{
			Username: "testuser",
			Password: "password123",
		}

		jsonValue, _ := json.Marshal(loginReq)
		req, _ := http.NewRequest(http.MethodPost, "/login", bytes.NewBuffer(jsonValue))
		req.Header.Set("Content-Type", "application/json")

		// 执行请求
		w := httptest.NewRecorder()
		router.ServeHTTP(w, req)

		// 断言响应
		assert.Equal(t, http.StatusOK, w.Code)
	})

	t.Run("Test Register Endpoint", func(t *testing.T) {
		// 创建测试路由
		router := gin.Default()
		router.POST("/register", authService.Register)

		// 准备测试数据
		registerReq := handlers.RegisterRequest{
			Username: "newuser",
			Password: "password123",
			Name:     "New User",
			Phone:    "13800138000",
			Role:     "student",
		}

		jsonValue, _ := json.Marshal(registerReq)
		req, _ := http.NewRequest(http.MethodPost, "/register", bytes.NewBuffer(jsonValue))
		req.Header.Set("Content-Type", "application/json")

		// 执行请求
		w := httptest.NewRecorder()
		router.ServeHTTP(w, req)

		// 断言响应
		assert.Equal(t, http.StatusOK, w.Code)
	})
}