package main

import (
	"fmt"
	"log"
	"time"

	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/config"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/database"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/models"
	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/utils"
)

func main() {
	// 加载配置
	config.LoadConfig()
	if config.GlobalConfig == nil {
		log.Fatal("Failed to load configuration")
	}

	// 初始化数据库
	database.InitDatabase()
	defer database.CloseDatabase()
	
	db := database.GetDB()

	// 测试用户数据
	testUsers := []struct {
		Username string
		Email    string
		Password string
		Nickname string
	}{
		{
			Username: "testuser",
			Email:    "test@example.com",
			Password: "Test@123",
			Nickname: "测试用户",
		},
		{
			Username: "student1",
			Email:    "student1@example.com",
			Password: "Student@123",
			Nickname: "学生一号",
		},
		{
			Username: "student2",
			Email:    "student2@example.com",
			Password: "Student@123",
			Nickname: "学生二号",
		},
		{
			Username: "teacher",
			Email:    "teacher@example.com",
			Password: "Teacher@123",
			Nickname: "教师账号",
		},
	}

	fmt.Println("开始创建测试用户...")

	for _, userData := range testUsers {
		// 检查用户是否已存在
		var existingUser models.User
		result := db.Where("username = ? OR email = ?", userData.Username, userData.Email).First(&existingUser)
		
		if result.Error == nil {
			fmt.Printf("用户 %s 已存在，跳过创建\n", userData.Username)
			continue
		}

		// 加密密码
		hashedPassword, err := utils.HashPassword(userData.Password)
		if err != nil {
			log.Printf("Failed to hash password for %s: %v", userData.Username, err)
			continue
		}

		// 创建用户
		user := models.User{
			Username:     userData.Username,
			Email:        userData.Email,
			PasswordHash: hashedPassword,
			Nickname:     &userData.Nickname,
			Status:       "active",
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
		}

		if err := db.Create(&user).Error; err != nil {
			log.Printf("Failed to create user %s: %v", userData.Username, err)
			continue
		}

		fmt.Printf("✓ 成功创建用户: %s (邮箱: %s, 密码: %s)\n", 
			userData.Username, userData.Email, userData.Password)
	}

	fmt.Println("\n测试用户创建完成！")
	fmt.Println("\n可用的测试账号：")
	fmt.Println("1. 用户名: testuser     邮箱: test@example.com       密码: Test@123")
	fmt.Println("2. 用户名: student1     邮箱: student1@example.com   密码: Student@123")
	fmt.Println("3. 用户名: student2     邮箱: student2@example.com   密码: Student@123")
	fmt.Println("4. 用户名: teacher      邮箱: teacher@example.com    密码: Teacher@123")
}
